Upload image with Axios to a Node.JS server

Asked

Viewed 12,477 times

4

I’m trying to upload an image using the library Axios, but she’s not getting into the back-end.

Image input

<input type="file" class="custom-file-input" id="file" name="file">

Note: My form already has the 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 data

return res.send(req.body);

Return of the API

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’s working.

1 answer

8


In Node.js we will use a middleware to handle files for the type multipart/form-data. I use the ladies.

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 on your . js on the front end, let’s adjust the object formData and we will not pass the field cpf "loose" along with the object formData, but yes we will insert the cpf within 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 separate resource chaves of valores when a form is submitted. Something similar to type application/x-www-form-urlencoded where the server knows the keys are separated by &, as an example:

nome=cardeal&cpf=12345678900

For the guy multipart/form-data, the boundary has a similar function to &.

Heed

For entities of type Multipart, the Boundary directive is mandatory.


The requisition was made in console.log in the Node.js terminal the following result is expected:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.