Content-Disposition
文件链接是直接预览还是下载取决于文件链接的响应头 Content-Disposition 的属性(参考文章)
在常规的 HTTP 应答中,Content-Disposition 响应标头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。
1 2 3 4 5 6
| Content-Disposition: inline
Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg"
|
代码实现
1、在线预览
对于复杂的预览场景,我们可以借助一下开源方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const previewPDF = (linkUrl: string) => {
var newWindow = window.open()
newWindow.document.write(`<img :src="${linkUrl}"/>`)
newWindow.document.write( `<iframe src="${linkUrl}" frameborder="0" width="100%" height="100%"></iframe>` )
newWindow.document.write( `<iframe frameborder="0" :src="'https://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(${linkUrl})" > </iframe>` ) }
|
2、下载文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const handleDownloadBtn = async (linkUrl: string, fileName: string) => { try { const response = await fetch(linkUrl) const blob = await response.blob()
const link = document.createElement('a') link.href = URL.createObjectURL(blob) link.download = `${fileName}.jpg` link.click() URL.revokeObjectURL(link.href) } catch (error: any) { ElMessage.error('下载文件失败!') } }
|