今天说一种vue下载二进制流文件的方法:后台直接返回文件的二进制内容,然后前端转化再下载。具体内容如下
instance.post(EXPORT_REPAYMENT_DETAIL, data, {
responseType: 'blob'
}).then((response) => {
if (response.status === 200) {
let blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
let objectUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
let disposition = response.headers['content-disposition']
let fileName = decodeURI(
disposition.split(";filename*=utf-8''")[1]
)
a.download = fileName
a.href = objectUrl
a.click()
a.remove()
let successMsg = this.$t('global_public.success')
this.$globalToast.popupMessage(successMsg, 2, 2000)
}
})
值得注意的是,请求接口时必加 “responseType: 'blob'”不然下载下来文件有问题
文件默认下载的为excel格式文件,其他文件请自行修改type类型
这里举例一些常用的类型
'ppt' => 'application/vnd.ms-powerpoint',
'dir' => 'application/x-director',
'js' => 'application/x-javascript',
'swf' => 'application/x-shockwave-flash',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/zip',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp3' => 'audio/mpeg',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'wav' => 'audio/x-wav',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'txt' => 'text/plain',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
1 条评论
看的我热血沸腾啊