Doing a PATCH with a file and some fields using multipart/form-data

↘锁芯ラ 提交于 2020-01-25 04:20:10

问题


I am doing a request to my server to patch some regular form fields as well as upload an image.

If I do these alone in separate requests all works perfectly, but nothing works if the form data and the file are in the same request. This is what it currently looks like:

const file = new FormData()
file.append('uploadedFile', uploadedFile, uploadedFile.name)
const patch = {
  name: 'Some Name',
  age: 18,
  file
}

return isomorphicFetch(`${MY_URL}`, {
    headers: {
      Accept: 'application/json'
    }
    method: 'PATCH',
    body: patch
  })

Here is what my middleware looks like:

const multipartMiddleware = multer({ dest: 'uploads/' })
  app.use('/myendpoint',
    multipartMiddleware.single('uploadedFile'),
    (req, res, next) => {
      console.log('REQ', req)
      req.feathers.file = req.file
      next()
    }
  )

Here is the thing: if I only put file as the body of my PATCH, it works just fine, I will have a req.file object in the middleware as expected, however, with the patch object I show in my example, I don't have a req.file object. What am I doing wrong? I would like to keep both my files and the name and age fields.

Keep in mind that if I split it into two calls, it works just as expected. For it to work, it currently looks like this:

// This code is the only way I can make my patches work:

const file = new FormData()
file.append('uploadedFile', uploadedFile, uploadedFile.name)
const patch = {
  name: 'Some Name',
  age: 18,
}

return Promise.all([
    isomorphicFetch(`${MY_URL}`, {
       headers: {
         Accept: 'application/json'
       },
        method: 'PATCH',
        body: patch
      }),
    isomorphicFetch(`${MY_URL}`, {
       headers: {
        Accept: 'application/json'
       },
        method: 'PATCH',
        body: file
      })
  ])

Update: I tried doing this through Postman, and it did in fact work. So I am even more confused now.

来源:https://stackoverflow.com/questions/54699108/doing-a-patch-with-a-file-and-some-fields-using-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!