如何使用axios将FormData和JSON数据发送到busboy

时间:2020-05-03 12:50:31

标签: node.js express axios busboy

我正在尝试使用相同的功能将图像上传到我的服务器并根据req.body.location变量存储图像URL ... 我正在使用busboy处理文件... 但是,我无法通过axios将正确的请求发送到服务器 正如您在代码中看到的那样,我发送了一个带有formData和位置的发布请求(formdata是formData obj) 我不知道busboy到底在哪里接收formdata,是否发送有效请求? 有什么建议吗?

       try {
        await axios({
          method: 'POST',
          URL: '.../api/uploadImage'
          data: {
            form: formData,
            location: 'profile'
           }
        })
      } catch (err) {
        console.log(err.response.data)
      }

    exports.uploadImage = (req, res) => {
  **// What should I do here?**
  const busboy = new BusBoy({ headers: req.headers })
  const imageLocation = req.body.location
  let imageFileName
  let imageToUpload
  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    if (
      mimetype !== 'image/jpeg' &&
      mimetype !== 'image/jpg' &&
      mimetype !== 'image/png' &&
      mimetype !== 'image/svg'
    ) {
      return res.status(400).json({
        status: 'error',
        message: 'Wrong file submitted',
      })
    }
    const imageExtension = filename.split('.')[filename.split('.').length - 1]
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`
    const filePath = path.join(os.tmpdir(), imageFileName)
    imageToUpload = {
      filePath,
      mimetype,
    }
    file.pipe(fs.createWriteStream(filePath))
  })
  busboy.on('finish', () => {
    admin
      .storage()
      .bucket()
      .upload(imageToUpload.filePath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToUpload.mimetype,
          },
        },
      })
      .then(() => {
        const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
        **// I know its updating the same location... doesn't matter right now =)**
        if (imageLocation === 'profile') db.doc(`/users/${req.user.usernameId}`).update({ imageUrl })
        if (imageLocation === 'hero') db.doc(`/users/${req.user.usernameId}`).update({ imageUrl })
      })
      .then(() => {
        return res.status(201).json({
          status: 'success',
          data: 'Image uploaded successfully',
        })
      })
      .catch((err) => {
        res.status(500).json({
          status: 'error',
          error: err.code,
        })
      })
  })
  busboy.end(req.rawBody)
}

0 个答案:

没有答案