A
A
Arseniy Kornilov2020-12-27 09:58:16
JavaScript
Arseniy Kornilov, 2020-12-27 09:58:16

How to accept a file in Node.js?

Good afternoon! I want the user to be able to update their profile photo, to work with files it costs multer to load them with fs , but the problem is that I can’t even correctly accept the file from the client

HTML form

<div id="img_preview" style="background-image: url();"></div>
<input type="file" name="img" class="file_hidden" id="change_img" readonly="" accept="image/*" onchange="Edit.encodeImageFileAsURL(this)">
<label for="change_img">Сменить фото</label>


JS
var file = document.querySelector("#change_img").files[0], form;
form = new FormData();
form.append("photo", file);
fetch('/upload', {
    method: 'post',
    body: form
}).then(function(res) {
    res.json().then(function(data) {
        if (data.status != "err") {
           //  successful response handler
        }
    });
}).catch(() => alert('Превышено время ожидание запроса!'));


NodeJS
app.use(multer({dest: __dirname + '/static/upload'}).single());

app.post('/upload', function(request, response) {
    if (!request.body) return response.sendStatus(400);
    console.log(request.body) // print undefined
    console.log(request.file) // print {}
});

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2020-12-27
@zkrvndm

Note that form.append() needs to be passed three parameters, not two.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question