项目中,我们经常遇到对文件的下载、预览功能。首先我们先说一下下载
一、文件的下载
1、后台根据数据生成word文件,存放到服务器,然后通过接口给前台返回地址,前台进行下载。该方法不足点就是,生成的文件会占据硬盘内存。
window.location = commonUrl + '/template/exportEvent?eventId=' + id + ''
2、后台给前台返回文件数据流,前端进行转换文件下载。
download(data, fileTitle) {
// fileTitle 文件名称
if (!data) {
return
}
const content = data
const blob = new Blob([content])
const fileName = fileTitle
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName + '.doc'
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob, { type: 'application/msword' })
document.body.appendChild(elink)
elink.click()
URL.revokeObjectUR