3

I have a Node.JS project with a server-side and a client-side powered by webpack. I was hoping to convert my project from a combination of axios/request to just use request, but I'm having issues doing file uploads from the browser. I'm using the request-promise library, but I have the same issue whether I'm using request or request-promise. My attempt is to do this:

return request.post({
  uri: `${BASE_URL}/files`,
  formData: {
    token: token,
    file: {value: filedata, options: {filename: filename}}
  }
})

where filedata is a File object returned from using an input tag to find a file on the user's computer. The error I get is:

TypeError: self._form.on is not a function

This seems to be because formData requires a readable stream from something like fs. How do I get the correct input to request?

2 Answers 2

1

add header in post request also, this will help to send your file with stream as you looking for.

return request.post({
  uri: `${BASE_URL}/files`,
  formData: {
    token: token,
    file: {value: filedata, options: {filename: filename}}
  },
  headers: {'enctype': 'multipart/form-data'}
})
Sign up to request clarification or add additional context in comments.

Comments

0

I found that this required a non-trivial solution to finally get working. I used a FileReader to convert the File object I received from the form into an ArrayBuffer. I manually set the headers to 'multipart/form-data' and used the multipart property to set up all my content. Finally, I needed this to all be wrapped in a Promise, so I had to set up the object and call resolve appropriately.

return new Promise((resolve) => {
  const fr = new FileReader()
  fr.onload = (event) => {
    return request({
      uri: `${BASE_URL}/files`,
      method: 'POST',
      headers: {
        'content-type': 'multipart/form-data'
      },
      multipart: {
        chunked: false,
        data: [
          {
            'Content-Disposition': 'form-data; name="token"',
            body: token
          },
          {
            'Content-Disposition': `form-data; name="file"; `filename="${filename}"`}`,
            body: event.target.result
          }
        ]
      }
    }).then(resolve)
  }
  fr.readAsArrayBuffer(filedata)
})

1 Comment

Gosh! reading the hole file into memory is no good, what if they upload 200+ mb or something. just use FormData and the promisified fetch api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.