简体   繁体   English

通过 ajax 将图像发送到 multer

[英]Sending image via ajax to multer

I'm using Multer to upload an image file into my node server, and it always comes back to giving me undefined for using ajax to send the image.我正在使用 Multer 将图像文件上传到我的节点服务器,它总是返回给我未定义的使用 ajax 发送图像。

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上传.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
    })
  }
})

I checked the image value with console and it shows C:\fakepath\Capture d'écran de 2019-09-19 11-33-59.png'我用控制台检查了图像值,它显示 C:\fakepath\Capture d'écran de 2019-09-19 11-33-59.png'

Would appreciate any help.将不胜感激任何帮助。

I think your server side code is fine, if I modify the client side code as below, everything works nicely, we end up with images in the /uploads folder:我认为您的服务器端代码很好,如果我修改客户端代码如下,一切正常,我们最终在 /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
    })
}

Solved!!!解决了!!!

getting value by通过获取价值

image = $("#input-file-img").val()

that means I was sending a type String as a file这意味着我将类型 String 作为文件发送

so I had to change it to所以我不得不把它改成

image = $('#input-file-img')[0].files[0]

and everything works really well一切都很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM