Home > Net >  Why my generated docx in javascript from a blob is filled with [Object Object]?
Why my generated docx in javascript from a blob is filled with [Object Object]?

Time:10-01

I'm sending data to my Django backend through a POST request, the server then creates a docx using this data and sends it back to me where I'm trying to download it using the following code :

axios.post(route, data).then((res) => {
    const filename = "report.docx"
    var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    var link = document.createElement('a');                     
    var URL = window.URL || window.webkitURL;
    var downloadUrl = URL.createObjectURL(blob);
    link.href = downloadUrl;
    link.style = "display: none";
    link.download = filename;
    document.body.appendChild(link)
    link.click()
    link.remove()       
});

The download of the file works but when I open it, it only contains [Object Object], what am I doing wrong here ? I checked the backend and the document is properly created as it has the right content when I'm saving it when it's generated in the server so it's either that i'm sending it badly or creating the file in the frontend badly.

Here is how I send it from the backend :

        #Generating the doc properly before this...
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    report_filename = 'graph-report-' now.strftime('%Y-%m-%d_%H-%M-%S') '.docx'
    response['Content-Disposition'] = 'attachment; filename=%s'%(report_filename)
    document.save(response)
    return response

Thanks for helping me.

CodePudding user response:

With Axios, the res in axios.post(route, data).then((res) => is a response object.

The returned data is found in res.data.

  1. Do console.log(res.data) to see that it truly is the binary data you expect.
  2. Do new Blob([res.data], ... to use that data to get the blob. (If it already is a blob courtesy of Axios, you don't necessarily need to bother.)

(As an aside, you don't really need to use fetch() and createObjectURL for this at all since you're forming a download-like binary response; it would be enough to just have the browser POST your desired data e.g. as a form to the endpoint; it would download the response just the same.)

  • Related