0

The way I have found examples are:

const file = fs.readFileSync(filePath)
const formData = new FormData()
formData.append('userId', userId)
formData.append('file', file)

const options = {
  method: 'post',
  url: 'http://localhost:5000/uploadFile',
  headers: {
    'content-type': 'multipart/form-data'
  },
  data: formData
}

await axios(options).then(res => { console.log(res) }).catch(err => { console.log(err) })

But this doesn't attach the file in request.files which is required for python. Since it doesn't attach it as file, the information about file type is also lost.

I have also tried using the following. It does attach the file to request.files but the contents are not of the proper file and all I get is a text string which assumingely is a buffer string output.

const file = new File(fs.readFileSync(filePath), fileName, { type: 'text/csv' })

The aim is to preserve the file type information so that server can save the file properly. What am I missing?

Note that the requests are not sent from nodejs (which has file access) directly.

Vikram Tiwari
  • 3,615
  • 1
  • 29
  • 39
  • As mentioned, I have tried using FormData to no avail. I don't need to pass filename because it's optional and I want to preserve the original filename (which is default behavior) – Vikram Tiwari Dec 11 '18 at 23:01
  • This thread shows a different way to upload a file: https://stackoverflow.com/a/43014086/1778465 – Get Off My Lawn Dec 11 '18 at 23:06
  • Also the 3rd parameter is optional when you are not passing a string. `fs.readFileSync(filePath)` returns a string, not a `Blob` or `File`. Basically you need to pass a `Blob` or `File` as param 2 not a string. – Get Off My Lawn Dec 11 '18 at 23:10
  • Possible duplicate of [NodeJS: sending/uploading a local file to a remote server](https://stackoverflow.com/questions/19818918/nodejs-sending-uploading-a-local-file-to-a-remote-server) – Get Off My Lawn Dec 11 '18 at 23:17
  • https://stackoverflow.com/questions/43013858 is doing it using html's input element which in my case, I don't have access to. https://stackoverflow.com/questions/19818918 does it directly via nodejs but I am trying to do it from browser. Not a duplicate. – Vikram Tiwari Dec 11 '18 at 23:39
  • This answer solved it. Closing. https://stackoverflow.com/a/50774380/1724300 – Vikram Tiwari Dec 12 '18 at 04:28
  • Possible duplicate of [sending file and json in POST multipart/form-data request with axios](https://stackoverflow.com/questions/50774176/sending-file-and-json-in-post-multipart-form-data-request-with-axios) – Vikram Tiwari Dec 12 '18 at 04:29

0 Answers0