Excel file corrupted on download with axios vuejs - javascript

I am trying to download an excel file. I have used axios for it.
I have tried the below code
axios.post(backendURL + 'api/client?file_name='+file_name,params, {
file_name: file_name
}, {
responseType: 'blob'
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data], {
type: 'application/vnd.ms-excel'
}))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', file_name)
document.body.appendChild(link)
link.click()
});
I am getting the error as "Excel cannot open the file "filename.xlsx" because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file"
I have tried all the solutions which I found in google but nothing worked. Please help

downloadFile() {
axios({
url: this.scenario.file, //.substring(0, this.scenario.file.lastIndexOf("/"))
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();
});
},

Related

Open blob file stored in indexDB on ios/Ipad

Hello i download file using axios like so.
return axios({
method: "get",
url: URL,
responseType: "blob",
})
.then((response) => {
return {
...val,
blob: response.data,
};
})
.catch((_) => {
onError(val);
});
After that i store it in indexDB using Dexie.
const { id } = dataToSave;
return db.files.put(dataToSave, id);
I have file in db like blob
Next i want to save it like so:
download(myBlob, title, mimeType);
i try using filesaver,downloadjs or manualy
const { title, blob, mimeType } = material;
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
// the filename you want
a.download = title;
document.body.appendChild(a);
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 1000);
It will download file only right after i download it to blob (browser session).
When i refresh page i get error WebkitBlobResource:1.
Any workaround of problem ? To either download file (pdf,html) or open it in new or same tab.
For now store data as arraybuffer, not blob works.

How download Excel file in Vue.js application correctly?

I'm struggling to download an Excel file in xlsx format in my Vue.js application. My Vue.js application make post request to the Node.js application which download that Excel file from remote SFTP server. Backend application works without any problems.
In Vue.js application I use next code:
axios.post(config.backendHost + '/excel', {
file_name: fileName
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data], {
type: 'application/vnd.ms-excel'
}))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
});
After downloading file by browser, file opens automatically and I am experiencing an error that looks like this:
We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?
You need to add the response type as a third argument in your post call
{
responseType: 'blob'
}
Your final code like that
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
responseType: 'blob'
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data], {
type: 'application/vnd.ms-excel'
}))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
});
Or you can use the library FileSaver.js to save your file
import FileSaver from 'file-saver'
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
responseType: 'blob'
}).then((response) => {
// response.data is a blob type
FileSaver.saveAs(response.data, fileName);
});
my case worked:
axios.get(`/api/v1/companies/${companyId}/export`, {
responseType: 'blob',
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute(
'download',
`${companyId}-${new Date().toLocaleDateString()}.xlsx`
)
document.body.appendChild(link)
link.click()
})

Download excel cannot open the file because the file format or file extension

const data = ('start_date=2019-07-04&end_date=2019-07-24');
axios({
url: `http://localhost:4000/report/data?${data}`,
method: 'GET',
responseType: "arraybuffer", // important
}).then(response => {
// BLOB NAVIGATOR
let blob = new Blob([response.data], { type: '' });
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.setAttribute('download', '');
document.body.appendChild(link);
link.download = [];
link.click();
document.body.removeChild(link);
}
});
I'm trying to download an xlsx file with reactJS but i'm receiving this message when i try to open my file after download:
"Excel can not open file 'file.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the file format"
Here's the frontend code:

Download PDF file forcefully instead of opening new tab using javascript

Here's what i've done so far. I managed to download the file but it's giving me "object%200%object" on the url when i try to open the file.
fetch({
url,
method: 'GET',
responseType: 'blob', // important
contentDisposition: 'attachment',
contentType: 'application/pdf',
mode: 'no-cors'
})
.then(r => r.blob())
.then((response) => {
console.log(response);
const s = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.setAttribute('download', `test.pdf`);
link.click();
});

How to convert the byte code to zip file in javascript

Im using the following code to convert the byte code to zip file but it does not download the actual xml and asc file send in the response , instead it just donwloads the standard zip contents , im not aware where i am going wrong , can anyone help me with this,
$http({
url:url,
method: requestType,
data:requestBody?requestBody:"",
headers: {
'Content-type': "application/json",
"SessionID":$rootScope.token
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
let blob = new Blob([data], {type: "application/zip"});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function (error) {
//upload failed
console.log(error);
});
this is not downloading the actual files at all. Can anyone help me through this. The byte cod ethat backend team is sending is as follows.
"PK:8xJMÆVÞ|xl/workbook.xml ¢( ÍnÂ0ïúÖ>#MpR­¸{C,²vdѾ}CR¢¶'n;³³fË«u磵göI­ñ«  ¡+8÷²AþÅvhú]mÐKwⶮµÄBxEwØ ­ñî<´GX¾s(oµ#6°|~b¬¼5;h¼úAöƽîÍd|ñ¿©rMbFVð~!îØ`nT10Wè~Ø4SäiÅÑ,ÇWøÁÿC|¼í¶ëÃzûL/ó4KËYZG0U:üþÂòPK:8xJnmt?Ø[Content_Types].xml ¢( ÅMNÃ0¯y·] vl¡\À²'ÕøGIiÏÆ#q& TUЪº²lÏ{ßõä·÷é|ãl
mð¥#×ÁX¿,EKU~#æ³éË6f\ê±5Q¼u
Na"x¾©Brx2*½RKÑèZêà <åÔyÙôÕ6=løxÀ²\dwC]±±Z_˵7¿ y¨*«ÁÝ:(5¹¦è×Â)ë¯zc¹ Áã _S¬ìk°¶w'~Äd
dèQ9öF¾´êBÙ/ãâ¼ÃîüÿkiÛ>þfå"Ç㿽Sç =ÉÞ']d£áºE
îdþ`s(}Oâ&K\­gJü=x?½wÈþ}PK
38xJ£ ²×rels/.rels ¢( ï»¿PK:8xJILE#¥¶xl/worksheets/sheet1.xml ¢( ¥ÛrÇEÅ÷èn\U\¡\q®ª%^ÿþõ˯ûÃ/·W»Ýñìÿ|"
Any help is appreciated. Thanks!
Seems like the issue is with the type parameter try with the below code
You can access the content-type from headers.
If it doesn't work, try with application/zip, application/octet-stream
$http({
url: url,
method: requestType,
data: requestBody ? requestBody : "",
headers: {
'Content-type': "application/json",
"SessionID": $rootScope.token
},
responseType: 'arraybuffer'
}).success(function(data, status, headers, config) {
let blob = new Blob([data], {
type: headers['content-type']
// OR
// type:"application/zip, application/octet-stream"
});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function(error) {
//upload failed
console.log(error);
});
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();

Categories