Grigory Voevodin
Grigory Voevodin

Reputation: 21

How to download response type document with axios on front-end application?

I am trying to get file from api (docx, odt) and save it to downloads (this is frontend app). I'v tried postman 'Save response to file' and it works ok, file saved as i expected. saving file with postman works ok What should I do in axios to downloand the response?

Response headers:

content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document,
content-disposition: attachment; filename="output_document.odt"
function getAllData() {
        let documentJSON = JSON.stringify(form);
        axios.post("http://testapi/document",
        {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/vnd.openxmlformats- 
                officedocument.wordprocessingml.document'
            },
            data: documentJSON
        })
        .then((response) => {
            console.log(response);
            const url = window.URL.createObjectURL(new 
            Blob([response.data], { type: 
            'application/vnd.openxmlformats- 
            officedocument.wordprocessingml.document' }));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.odt'); 
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error))

I don't rly understand what is going on with response so I tried different things, for example to create blob from it (which is obviously incorrect)...

Upvotes: 0

Views: 1050

Answers (1)

Grigory Voevodin
Grigory Voevodin

Reputation: 21

So, i'v just used wrong sintax of axios post request, it did not apply neither request headers and body, nor response type: correct sintax is:

axios.post("http://176.32.33.67:8000/api/document/file",
    documentJSON,
    {
        responseType: 'arraybuffer',
        headers: {
            'Content-Type': 'application/json',
            //'Accept': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        }
    })
    .then((response) => {
        console.log(response);
        //deal with response
    }

Upvotes: 0

Related Questions