Reputation: 5494
I try to create an XLSX file in a Vue application with axios. I do this:
First I send a post call to the backend controller:
return axios({
url: '/backend/article/exportApi',
method: 'POST',
reponseType: 'blob',
headers: {
'Accept': 'vnd.ms-excel'
},
data: {headers: headers, articles: articles}
});
Then on the backend I do some things, create a xlsx file and save it on the server. This file is good and I when I check it, I can open it in excel. Now I want that this file is automatically downloaded by the browser, so in my controller I do this ($file is the path to the created xlsx file on the server):
$response = $this->Response();
$response->setHeader('Cache-Control', 'public');
$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-disposition', 'attachment; filename="export.xlsx"');
$response->setHeader('Content-Type', 'application/vnd.ms-excel');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', filesize($file));
$response->sendHeaders();
echo readfile($file);
The response looks like this: https://d.pr/i/UndMRn On the JS side I do this with the response:
let blob = new Blob([response.data], {type: 'vnd.ms-excel;charset=utf-8'});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'export.xlsx';
link.click();
The file which is downloaded is corrupted and can not be opened by Excel. I tried several things, including changing the type from vnd.ms-excel
to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
and the responseType
from blob
to arraybuffer
. None with success.
Anybody has a solution?
Upvotes: 1
Views: 2716
Reputation: 5494
The reason was that POST does not accept a responseType. So I needed to make a POST call first and a GET request afterwards to retrieve and create the file.
Upvotes: 1