最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

通过ajax发送图像到multer

IT培训 admin 4浏览 0评论

通过ajax发送图像到multer

[我正在使用Multer将图像文件上传到我的节点服务器,并且总是会因为使用ajax发送图像而给我未定义的含义。

Ajax:

image = $("#input-file-img").val()
                const data = new FormData();
                 data.append("image", image);
                 $.ajax({
                    url: '/uploadfile/' + userName,
                    method: 'POST',
                    async: false,
                    processData: false ,
                    contentType: false,
                    data: data
                })

Upload.js

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})
var upload = multer({ storage: storage })

router.post('/uploadfile/:userName', upload.single('image'), async (req, res, next) => {
  let user = await User.findOne({ userName: req.params.userName })
  let file = req.file
  let fileName = file.filename
  let path = variables.kepler + 'uploads/' + fileName
  user.image = path
  await user.save()
  if (!path) {
    const error = new Error('Please upload a file ...')
    error.httpStatusCode = 400
    return next(error)
  }

  if (path) {
    return res.status(200).send({
      status: '200',
      message: 'Operation completed successfully ...',
      data: user,
      path
    })
  }
})

[我用控制台检查了图像值,它显示了C:\ fakepath \ Capture d'écrande 2019-09-19 11-33-59.png'

非常感谢您的帮助。

回答如下:

[我认为您的服务器端代码很好,如果我按如下所示修改客户端代码,一切正常,我们最终在/ uploads文件夹中找到图像:

function base64toBlob(base64, mimeType) {
    const bytes = atob(base64.split(',')[1]);
    const arrayBuffer = new ArrayBuffer(bytes.length);
    const uintArray = new Uint8Array(arrayBuffer);
    for (let i = 0; i < bytes.length; i++) {
        uintArray[i] = bytes.charCodeAt(i);
    }
    return new Blob([ arrayBuffer ], { type: mimeType });
}

function submitForm() {         
    const imgRegEx = /^data:(image\/(gif|png|jpg|jpeg))/;
    const imageData = $('#input-file-img').attr('src');
    const mimeType = imgRegEx.exec(imageData)[1];
    const blob = base64toBlob(imageData, mimeType);

    const fileExt = mimeType.replace("image/", "");
    const fileName = "test-image." + fileExt; // Change as appropriate..

    const data = new FormData();
    data.append("image", blob, fileName);

    $.ajax({
        url: '/uploadfile/' + userName,
        method: 'POST',
        async: false,
        processData: false ,
        contentType: false,
        data: data
    })
}

通过ajax发送图像到multer

[我正在使用Multer将图像文件上传到我的节点服务器,并且总是会因为使用ajax发送图像而给我未定义的含义。

Ajax:

image = $("#input-file-img").val()
                const data = new FormData();
                 data.append("image", image);
                 $.ajax({
                    url: '/uploadfile/' + userName,
                    method: 'POST',
                    async: false,
                    processData: false ,
                    contentType: false,
                    data: data
                })

Upload.js

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})
var upload = multer({ storage: storage })

router.post('/uploadfile/:userName', upload.single('image'), async (req, res, next) => {
  let user = await User.findOne({ userName: req.params.userName })
  let file = req.file
  let fileName = file.filename
  let path = variables.kepler + 'uploads/' + fileName
  user.image = path
  await user.save()
  if (!path) {
    const error = new Error('Please upload a file ...')
    error.httpStatusCode = 400
    return next(error)
  }

  if (path) {
    return res.status(200).send({
      status: '200',
      message: 'Operation completed successfully ...',
      data: user,
      path
    })
  }
})

[我用控制台检查了图像值,它显示了C:\ fakepath \ Capture d'écrande 2019-09-19 11-33-59.png'

非常感谢您的帮助。

回答如下:

[我认为您的服务器端代码很好,如果我按如下所示修改客户端代码,一切正常,我们最终在/ uploads文件夹中找到图像:

function base64toBlob(base64, mimeType) {
    const bytes = atob(base64.split(',')[1]);
    const arrayBuffer = new ArrayBuffer(bytes.length);
    const uintArray = new Uint8Array(arrayBuffer);
    for (let i = 0; i < bytes.length; i++) {
        uintArray[i] = bytes.charCodeAt(i);
    }
    return new Blob([ arrayBuffer ], { type: mimeType });
}

function submitForm() {         
    const imgRegEx = /^data:(image\/(gif|png|jpg|jpeg))/;
    const imageData = $('#input-file-img').attr('src');
    const mimeType = imgRegEx.exec(imageData)[1];
    const blob = base64toBlob(imageData, mimeType);

    const fileExt = mimeType.replace("image/", "");
    const fileName = "test-image." + fileExt; // Change as appropriate..

    const data = new FormData();
    data.append("image", blob, fileName);

    $.ajax({
        url: '/uploadfile/' + userName,
        method: 'POST',
        async: false,
        processData: false ,
        contentType: false,
        data: data
    })
}

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论