Vue+Laravel : 如何下载pdf文件?
现状:
前端:Vue。后端:Laravel。
在网络应用程序内部,我需要让用户下载某些pdf文件:
- 我需要Laravel来获取文件并将其作为API GET请求的响应返回。
- 然后,在我的Vue Web应用程序中,我需要获取文件并下载它。
代码:
API:
$file = public_path() . "/path/test.pdf";$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'test.pdf', $headers);
网络应用程序:
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()
})
}
结果:
使用此代码,我确实设法下载了pdf文件。问题是pdf是空白的。
数据以某种方式被破坏(这不是特定的pdf文件的问题,我已经尝试使用多个pdf文件-相同的结果)
来自服务器的响应:
来自服务器的响应本身很好:
PDF:
问题可能出在pdf文件上。它肯定看起来已损坏的数据。这是response.data
的外观摘录:
问题:
如何使用Laravel的API和Vue的Web应用程序正确下载pdf文件?
谢谢!
最佳答案
解决方案:
上面的代码是正确的。缺少的是将适当的responseType
添加为arraybuffer
。
我被响应中的????
吓到了,这误导了我。
这些问号没问题,因为pdf是二进制数据,并且应由适当的读者阅读。
传票者:
而arraybuffer恰好用于保留二进制数据。
这是来自mozilla网站的定义:
The ArrayBuffer object is used to represent a generic, fixed-lengthraw binary data buffer. You cannot directly manipulate the contents of
an ArrayBuffer; instead, you create one of the typed array objects or
a DataView object which represents the buffer in a specific format,
and use that to read and write the contents of the buffer.
ResponseType
字符串指示响应的类型。通过告诉它一个arraybuffer,然后它会相应地处理数据。
仅仅通过添加responseType,我就设法正确下载了pdf文件。
代码:
这是经过更正的Vue代码(与以前完全一样,但增加了responseType):
downloadFile() {this.$http.get(this.appApiPath + '/testpdf', {responseType: 'arraybuffer'})
.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()
})
}
编辑:
这是一个更完整的解决方案,其中考虑了其他浏览器的行为:
downloadContract(booking) {this.$http.get(this.appApiPath + '/download_contract/' + booking.id, {responseType: 'arraybuffer'})
.then(response => {
this.downloadFile(response, 'customFilename')
}, response => {
console.warn('error from download_contract')
console.log(response)
// Manage errors
}
})
},
downloadFile(response, filename) {
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([response.body], {type: 'application/pdf'})
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob)
return
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob)
var link = document.createElement('a')
link.href = data
link.download = filename + '.pdf'
link.click()
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data)
}, 100)
},
以上是 Vue+Laravel : 如何下载pdf文件? 的全部内容, 来源链接: www.h5w3.com/121894.html