通过ajax发送图像到multer

我正在使用 Multer 将图像文件上传到我的节点服务器,它总是返回给我 undefined 使用 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

                })

上传.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'écran de 2019-09-19 11-33-59.png'


将不胜感激任何帮助。


LEATH
浏览 149回答 2
2回答

MMMHUHU

解决了!!!通过获取价值image = $("#input-file-img").val()这意味着我正在将类型字符串作为文件发送所以我不得不把它改成image = $('#input-file-img')[0].files[0]一切都很好

慕森卡

我认为你的服务器端代码很好,如果我修改客户端代码如下,一切正常,我们最终在 /uploads 文件夹中得到图像:function base64toBlob(base64, mimeType) {&nbsp; &nbsp; const bytes = atob(base64.split(',')[1]);&nbsp; &nbsp; const arrayBuffer = new ArrayBuffer(bytes.length);&nbsp; &nbsp; const uintArray = new Uint8Array(arrayBuffer);&nbsp; &nbsp; for (let i = 0; i < bytes.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; uintArray[i] = bytes.charCodeAt(i);&nbsp; &nbsp; }&nbsp; &nbsp; return new Blob([ arrayBuffer ], { type: mimeType });}function submitForm() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; const imgRegEx = /^data:(image\/(gif|png|jpg|jpeg))/;&nbsp; &nbsp; const imageData = $('#input-file-img').attr('src');&nbsp; &nbsp; const mimeType = imgRegEx.exec(imageData)[1];&nbsp; &nbsp; const blob = base64toBlob(imageData, mimeType);&nbsp; &nbsp; const fileExt = mimeType.replace("image/", "");&nbsp; &nbsp; const fileName = "test-image." + fileExt; // Change as appropriate..&nbsp; &nbsp; const data = new FormData();&nbsp; &nbsp; data.append("image", blob, fileName);&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: '/uploadfile/' + userName,&nbsp; &nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; async: false,&nbsp; &nbsp; &nbsp; &nbsp; processData: false ,&nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; data: data&nbsp; &nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript