Answer the question
In order to leave comments, you need to log in
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>
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('Превышено время ожидание запроса!'));
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 {}
});
Answer the question
In order to leave comments, you need to log in
Note that form.append() needs to be passed three parameters, not two.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question