fastify-file-upload icon indicating copy to clipboard operation
fastify-file-upload copied to clipboard

Missing data in body (ignored other values to files)

Open VeeeneX opened this issue 4 years ago • 3 comments

We're sending data as in example bellow, due to this line:

     if (request.raw.files) {
        for (const key in request.raw.files) {
          request.body[key] = request.raw.files[key]
        }
      }

They got ignored and therefore not added into body, so I hope this helps somebody, @huangang maybe consider adding following :slightly_smiling_face:

import fp from 'fastify-plugin'
import fileUpload from 'express-fileupload'

const setMultipart = (request, done): void => {
  request[Symbol('multipart')] = true
  done()
}

const fastifyUpload = (fastify, options, done) => {
  fastify.addContentTypeParser('multipart', setMultipart)

  options = options || {}
  fastify.use(fileUpload(options))

  fastify.addHook('preValidation', (request, reply, done) => {
    if (request.raw) {
      !request.body && (request.body = request.raw.body || {})
      if (request.raw.files) {
        request.body = { ...request.raw.body, ...request.raw.files }
      }
    }
    done()
  })
  done()
}

export default fp(fastifyUpload, {
  fastify: '>= 2.0.0',
  name: 'fastify-file-upload'
})

Example request

PUT http://localhost:3000/registration/938cecf7-fa10-4580-a4bd-978ca34f3b67
Content-Type: multipart/form-data; boundary=WebAppBoundary
x-token: vDkhBTJCwsdov0t55bzu4UHIN9AXZgYJGz3Fq326Rske8ZCm

--WebAppBoundary
Content-Disposition: form-data; name="files"; filename="logo.png"
Content-Type: image/png

< ./input.pdf

--WebAppBoundary
Content-Disposition: form-data; name="files"; filename="logo.png"
Content-Type: image/png

< ./input.png

--WebAppBoundary
Content-Disposition: form-data; name="data"

{}
--WebAppBoundary--

VeeeneX avatar Jul 16 '20 14:07 VeeeneX

Can you provide an example repositories? I want to try

huangang avatar Jul 21 '20 05:07 huangang

Suppose the backend needs to receive the imageKey field, array type, and the frontend uses formdata to pass it.

imageKey has strings and streams of files,

Now that raw.files overwrites the body, the string part of imageKey is missing.

niumowangorz avatar May 11 '23 02:05 niumowangorz

4.0.0 also has bugs, waiting to be updated by the author

niumowangorz avatar May 11 '23 02:05 niumowangorz