THE SITUATION:
前端:VUE.后端:Laravel.
Inside the web app I need to let the user download certain pdf files:
- I need Laravel to take the file and return it as a response of an API GET request.
- Then inside my Vue web app I need to get the file and download it.
THE CODE:
API:个
$file = public_path() . "/path/test.pdf";
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'test.pdf', $headers);
Web app:个
downloadFile() {
this.$http.get(this.apiPath + '/download_pdf')
.then(response => {
let blob = new Blob([response.data], { type: 'application/pdf' })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'test.pdf'
link.click()
})
}
OUTCOME:个
使用这段代码,我确实下载了一个pdf文件.问题是pdf是空白的.
不知怎的,数据被 destruct 了(这不是这个特定pdf文件的问题,我try 了几个pdf文件——结果相同)
RESPONSE FROM SERVER:
服务器本身的响应正常:
PDF:
The problem may be with the pdf file. It definitely looks corrupted data. This is an excerpt of how it looks like the response.data
:
THE QUESTION:个
How can I properly download a pdf file using Laravel for the API and Vue for the web app?
谢谢!