Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending file and json in POST multipart/form-data request with axios

I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.

doAjaxPost() {
    var formData = new FormData();
    var file = document.querySelector('#file');

    formData.append("file", file.files[0]);
    formData.append("document", documentJson);

    axios({
        method: 'post',
        url: 'http://192.168.1.69:8080/api/files',
        data: formData,
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (response) {
        console.log(response);
    });
}

However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type field for document, while for file field Content-Type is application/pdf (I'm sending a pdf file).

Request shown in network inspector

On the server Content-Type for document is text/plain;charset=us-ascii.

Update:

I managed to make a correct request via Postman, by sending document as a .json file. Though I discovered this only works on Linux/Mac.

like image 233
pavlee Avatar asked Jun 09 '18 12:06

pavlee


3 Answers

To set a content-type you need to pass a file-like object. You can create one using a Blob.

const obj = {
  hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
  type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
  method: 'post',
  url: '/sample',
  data: data,
})
like image 117
Quentin Avatar answered Nov 12 '22 13:11

Quentin


Try this.

doAjaxPost() {
    var formData = new FormData();
    var file = document.querySelector('#file');

    formData.append("file", file.files[0]);
    // formData.append("document", documentJson); instead of this, use the line below.
    formData.append("document", JSON.stringify(documentJson));

    axios({
        method: 'post',
        url: 'http://192.168.1.69:8080/api/files',
        data: formData,
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (response) {
        console.log(response);
    });
}

You can decode this stringified JSON in the back-end.

like image 36
Fullstack Engineer Avatar answered Nov 12 '22 14:11

Fullstack Engineer


you only need to add the right headers to your request

axios({
  method: 'post',
  url: 'http://192.168.1.69:8080/api/files',
  data: formData,
  header: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
          },
    })
like image 2
eth3rnit3 Avatar answered Nov 12 '22 13:11

eth3rnit3