A
A
Alexander Tumaykin2016-05-21 22:00:00
Node.js
Alexander Tumaykin, 2016-05-21 22:00:00

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));

file object:
let file = {
    name: 'test.jpg',
    path: 'D:\test.jpg'
}

Spent hours googling hints to no avail. Most options come down to using . And using the File object obtained in this way.
The server has a working PHP script that should accept the file via $_FILES; So far this has not been achieved.
If we greatly simplify the task, that is, there is a js file that, with "node test.js", should send a local file to the server with PHP
ps in the headers, in this case the following is transmitted:
------WebKitFormBoundaryDKpQTS4WNgpByUYC
Content-Disposition: form-data; name="newName"

test.jpg
------WebKitFormBoundaryDKpQTS4WNgpByUYC
Content-Disposition: form-data; name="file"


------WebKitFormBoundaryDKpQTS4WNgpByUYC--

And accordingly on the server:
var_dump($_FILES);

//
array()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Tumaykin, 2016-05-22
@alexandrtumaykin

Found a solution.

data.append('file', new Blob([fs.readFileSync(file.path)]), file.name);

T
titronfan, 2016-05-21
@titronfan

Look at the package https://github.com/expressjs/multer
At the same time, you can try to connect fetch to it.

#
#algooptimize #bottize, 2016-05-22
@user004

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 question

Ask a Question

731 491 924 answers to any question