文件的下载与预览
发布时间 2024-03-24 13:36:20

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) => {
// 本地文件
// window.open(localUrl, '_blank')

// 打开新窗口或标签页
var newWindow = window.open()
// 在新窗口或标签页中写入 HTML

// 1、图片
newWindow.document.write(`<img :src="${linkUrl}"/>`)

// 2、pdf
newWindow.document.write(
`<iframe src="${linkUrl}" frameborder="0" width="100%" height="100%"></iframe>`
)

// 3、doc、excel等
// - 使用微软提供的服务
newWindow.document.write(
`<iframe
frameborder="0"
:src="'https://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(${linkUrl})"
>
</iframe>`
)
// 【也可以自建服务:https://github.com/kekingcn/kkFileView】
}

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('下载文件失败!')
}
}
上一页
2024-06-11 00:39:23
下一页