Last active
October 4, 2023 14:35
-
-
Save binki/10ac3e91851b524546f8279733cdadad to your computer and use it in GitHub Desktop.
posting a file loaded through fs.readFile() through axios+form-data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const axios = require('axios'); | |
const FormData = require('form-data'); | |
const fs = require('fs'); | |
const filePath = __dirname + '/../accept-http-post-file/cookie.jpg'; | |
fs.readFile(filePath, (err, imageData) => { | |
if (err) { | |
throw err; | |
} | |
const form = new FormData(); | |
form.append('file', imageData, { | |
filepath: filePath, | |
contentType: 'image/jpeg', | |
}); | |
axios.post('http://localhost:3000/endpoint', form, { | |
headers: form.getHeaders(), | |
}).then(response => { | |
console.log('success! ', response.status, response.statusText, response.headers, typeof response.data, Object.prototype.toString.apply(response.data)); | |
}).catch(err => { | |
console.log(err); | |
}); | |
}); |
Sorry for this super late and likely now useless response ;-). But, yes, if you need to support arbitrary file sizes, you are pretty much forced to use something like createReadStream()
on the client and createWriteStream()
on the server. Doing this and adding error handling and cleanup gets into a more complicated solution which I would spend time on if I needed to do it myself, but I don’t need to at the moment ;-). Sorry, and I hope that my earlier response was enough to get you somewhere!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lluisemper
readFile()
and nodejs-styleBuffer
only exist in a nodejs environment.USVString
and alsoBlob
only exist in a browser environment. Theform-data
nodejs module is meant to look similar to the DOM (browser environment) class in usage. This is because the DOM API is something that people are familiar with. But it does not support and is not intended to be used in the browser environment. It is nodejs-oriented. See its documentation forFormData.append()
for information on the types of arguments you may pass to theform-data
npmjs module’sFormData
class.