Answer the question
In order to leave comments, you need to log in
How to send file from node js via fetch and formdata?
Good afternoon.
I am making an application on Electron and need to send a local file to the server.
From the input data, there is an array with names and paths to files on the computer. Those. need to send files without using File Input in Html. The task needs to be solved purely on NodeJS. Preferably using fetch
An example of my code in a simplified form:
let data = new FormData();
data.append('newName', file.name);
data.append('file', fs.readFileSync(file.path), file.name);
fetch(url, {
method: 'POST',
body: data
})
.then(console.log.bind(console));
let file = {
name: 'test.jpg',
path: 'D:\test.jpg'
}
------WebKitFormBoundaryDKpQTS4WNgpByUYC
Content-Disposition: form-data; name="newName"
test.jpg
------WebKitFormBoundaryDKpQTS4WNgpByUYC
Content-Disposition: form-data; name="file"
------WebKitFormBoundaryDKpQTS4WNgpByUYC--
var_dump($_FILES);
//
array()
Answer the question
In order to leave comments, you need to log in
Found a solution.
data.append('file', new Blob([fs.readFileSync(file.path)]), file.name);
Look at the package https://github.com/expressjs/multer
At the same time, you can try to connect fetch to it.
I hope I didn’t blunt it for the third time) I
looked at the form data code, the parameters are not set correctly when filling in files,
here I see such an example
stackoverflow.com/questions/25344879/uploading-fil...
Look also
form.append('file', '', {
filename: 'myfile.txt',
contentType: 'text/plain'
});
or
form.append('file', fs.createReadStream(filepath));
----------------------
var FormData = require('form-data');
varFs = require('fs');
var Fetch = require('node-fetch');
fs.debug = true;
var Form = new FormData();
Form.append('my_field', 'myvalue');
form.append('
Fs.createReadStream('C:\\Users\\user\\documents\\visual studio 2015\\' +
'Projects\\android.forms.test\\NodejsConsoleApp1\\app.js'));
Fetch(' myip.ru ',
{
method: 'POST',
body: Form
});
Checked personally
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question