文件下载实现方法
方法一:
适合后台服务器文件已存在,直接下载已有文件。
如附件上传后,再下载等情况
// GET下载文件
// url:下载链接,请求地址?参数名=参数
// fileName:下载名和格式
export function downloadFile(url, fileName) {
const xhh = new XMLHttpRequest()
xhh.open('get', process.env.VUE_APP_BASE_API + url)
xhh.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'))
xhh.setRequestHeader('Content-Type', 'application/json')
xhh.responseType = 'blob'
xhh.onreadystatechange = function() {
if (xhh.readyState === 4 && xhh.status === 200) {
var mimeType = xhh.getResponseHeader('ajax-mimeType')
var blob = new Blob([xhh.response], { type: mimeType })
var csvUrl = URL.createObjectURL(blob)
var link = document.createElement('a')
document.body.appendChild(link)
link.href = csvUrl
link.target = '_blank'
link.id = 'linkId'
link.className = 'linkId'
link.download = fileName
document.getElementById('linkId').click()
link.remove()
}
}
xhh.send()
}
方法二:
适合后台返回文件流,前台接收后转成指定文件格式。
如列表数据的导出等。
api接口:特别注意responseType为bold类型,不然文件可能打不开
export function exportFile(params) {
return request({
url: '/xxxxxxxx',
method: 'get',
params: params,
responseType: 'blob'
})
}
接口调用:
const type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8'
exportRecruit({ businessType: 0 }).then((rsp) => {
this.loading = false
streamDownloadFile(rsp, `招聘信息.xlsx`, type)
}).catch((e) => {
this.loading = false
})
export function streamDownloadFile(content, fileName, type) {
const url = window.URL.createObjectURL(new Blob([content], {
type: type
}))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
文件类型type指定:
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf application/rtf
.xls application/vnd.ms-excel application/x-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps application/vnd.ms-powerpoint
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf application/pdf
.swf application/x-shockwave-flash
.dll application/x-msdownload
.exe application/octet-stream
.msi application/octet-stream
.chm application/octet-stream
.cab application/octet-stream
.ocx application/octet-stream
.rar application/octet-stream
.tar application/x-tar
.tgz application/x-compressed
.zip application/x-zip-compressed
.z application/x-compress
.wav audio/wav
.wma audio/x-ms-wma
.wmv video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg audio/mpeg
.rm application/vnd.rn-realmedia
.mid .midi .rmi audio/mid
.bmp image/bmp
.gif image/gif
.png image/png
.tif .tiff image/tiff
.jpe .jpeg .jpg image/jpeg
.txt text/plain
.xml text/xml
.html text/html
.css text/css
.js text/javascript
.mht .mhtml message/rfc822

浙公网安备 33010602011771号