I want to send a file from a server to an other.
The problem is that my second server (who receive) don’t read correctly my file.
Normally I send my file to an API but I create a little server to make my own tests.
My server (sender):
First I got my file with multer().single('file')
(My file only contain "Hello")
const formData = new FormData();
const file = new File(req.file.buffer, req.file.originalname, { type: req.file.mimetype })
formData.append("file", file);
let firstFile = null;
for (const [key, value] of formData.entries()) {
if (value instanceof File) {
firstFile = value;
break;
}
}
const uploadres = await fetch(url, {
method: "POST",
headers: {
"Authorization": "Bearer " + token,
"Content-type": "multipart/form-data"
},
body: firstFile
})
Then I read the file like this :
var body;
body = '';
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log(req.method + ' ' + req.url + ' HTTP/' + req.httpVersion);
for (prop in req.headers) {
console.log(toTitleCase(prop) + ': ' + req.headers[prop]);
}
if (body.length > 0) {
if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
body = decodeURIComponent(body)
}
console.log('n' + body);
}
console.log('');
res.writeHead(200);
res.end();
});
my server print: "72101108108111"
I know that something was wrong in my code because the API receive my file but don’t doesn’t perform normally.
I think my problem become from encoding but I don’t know how to fix that.
I have try a lot of things, like change my file with another etc. but nothing works.
2
Answers
As you are sending a file you should maybe try to encoding type your request as "multipart/form-data"
It looks like "72101108108111" is the decimal representation of the ASCII encoding of the characters "Hello".
It might help to update the second code snippet to parse the data as a binary buffer instead of a string.
replace
body = '';
withlet body = []
replace
body += chunk
withbody.push(chunk)
add
body = Buffer.concat(body)
to the first line of the.on('end'
callbackand then use the
.toString()
to see the result