Yauheni
Yauheni

Reputation: 83

Vue js downloaded excel file is corrupted

I have problem with excel file download in Vue. The url in the backend seeems to be ok: "file" parameter stores my url in the object this.scenario.file = "http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx"

            downloadFile() {
            axios({
                url: this.scenario.file,
                method: "GET",
                headers: {"Accept": "application/vnd.ms-excel"},
                responseType: "blob"
            }).then(response => {
                const fileURL = window.URL.createObjectURL(new Blob([response.data]));
                const fileLink = document.createElement("a");

                fileLink.href = fileURL;
                fileLink.setAttribute("download", "file.xlsx");
                document.body.appendChild(fileLink);

                fileLink.click();
            });
        },

And below response object details:

myresponce:Object
config:Object
adapter:ƒ xhrAdapter(config)
data:undefined
headers:Object
Accept:"application/vnd.ms-excel"
maxContentLength:-1
method:"get"
responseType:"arraybuffer"
timeout:0
transformRequest:Array[1]
0:ƒ transformRequest(data, headers)
transformResponse:Array[1]
0:ƒ transformResponse(data)
url:"http://127.0.0.1:8000/media/datafiles/
Input_curves_bm7ionE.xlsx"
validateStatus:ƒ validateStatus(status)
xsrfCookieName:"XSRF-TOKEN"
xsrfHeaderName:"X-XSRF-TOKEN"
data:ArrayBuffer
headers:Object
content-length:"1345"
content-type:"text/html; charset=utf-8"
date:"Sun, 07 Jun 2020 22:44:10 GMT"
server:"WSGIServer/0.2 CPython/3.7.7"
vary:"Cookie"
x-content-type-options:"nosniff"
x-frame-options:"DENY"
request:XMLHttpRequest
status:200
statusText:"OK"

Upvotes: 1

Views: 1621

Answers (1)

Va54
Va54

Reputation: 111

You can try something like this.

axios({
                url: this.scenario.file,
                method: "GET",
                headers: {"Accept": "application/vnd.ms-excel"},
                responseType: "arraybuffer"
            }).then(response => {
                const url = window.URL.createObjectURL(
            new Blob([response.data], {type: "application/csv"})
        );
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", `file.xlsx`);

        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        link.remove();
            });

Upvotes: 2

Related Questions