Image Upload with Axios to a Node server.JS
I'm trying to upload an image using the Axios library, but it's not coming to the back end.
Image input
<input type="file" class="custom-file-input" id="file" name="file">
Note: my form is already with enctype="multipart/form-data"
JQuery Code
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('http://localhost:3030/api/admin/employees', {
cpf,
formData
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
});
Node.js returning the data
return res.send(req.body);
API return
config: {
url: "http://localhost:3030/api/admin/employees",
method: "post",
data: "{"cpf":"321.321.321-32","formData":{}}",
headers: {…}, transformRequest: Array(1), …
}
data: {}
headers: {content-length: "2", content-type: "application/json; charset=utf-8"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
I've tried many ways but nothing is working.
1 answers
No Node.js let's use a middleware to handle files for Type multipart/form-data
. I use the multer .
For the app.js:
const multer = require("multer");
...
...
let upload = multer();
// Esta é a rota a ser usada pelo 'axios': http://localhost:3000/image-upload.
// O campo 'fileimage' será a chave que o multer irá
// procurar pelo arquivo de imagem.
app.post("/image-upload", upload.single('fileimage'), (req, res) => {
console.log(req.body);
console.log(req.file);
res.status(200).json({ message: "success!" });
});
Now in your .js on the front end, we will adjust the object formData
and we will not pass the field cpf
"loose" along with the object formData
, but we will insert the cpf
inside the formData
:
const formData = new FormData();
const imagefile = document.querySelector("#file");
// 'fileimage' é o campo que o 'multer' procura o arquivo de imagem.
formData.append("fileimage", imagefile.files[0]);
formData.append("cpf", '1234567890'); // cpf junto ao formData.
axios.post("http://localhost:3000/image-upload", formData, {
headers: {
"Content-Type": `multipart/form-data; boundary=${formData._boundary}`,
}
}).then(response => console.log(response));
The parameter boundary
serves as a resource to separate chaves
from valores
when a form is submitted. Something similar to type application/x-www-form-urlencoded
where the server knows that the keys are separated by &
, as an example:
nome=cardeal&cpf=12345678900
For Type multipart/form-data
, boundary
has a function similar to &
.
Attention
For entities of type multipart, the boundary directive is mandatory.
Made the request, at console.log
in the node terminal.js the following result is expected: