I use Laravel 10.x and Vue.js 3.x with PHPWord package for my project. I would like to download a generated docx file. The download is successful, but I cannot open the file - it is corrupted.
I have tried adding ob_end_clean() as it is mentioned in many questions & answers about downloading corrupted files from Laraval storage, but the problem is not solved. I also downloaded the generated file using scp, and it is not corrupted. So the problem is obviously somewhere in the response and not in using template and saving the file.
Vue.js
const getFile = async () => {
try {
let response = await axios.get('api/docx', { responseType: 'blob' });
let blob = new Blob([response.data]);
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'test.docx';
document.body.appendChild(link);
link.click();
} catch (e) {
alert(e);
}
}
Laravel
public function getFile() {
$doc = new TemplateProcessor(storage_path() . '/app/public/test_template.docx');
$doc->setValue('random_text', 'Foo');
$doc->saveAs(storage_path() . '/app/public/test.docx');
ob_end_clean();
$headers = array('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
return response()->download(storage_path() . '/app/public/test.docx', 'test.docx', $headers);
}
Vue