1.添加下载按钮
2.(原始方法,会出现乱码)给按钮添加点击事件,添加接口代码
download: function() {
const row = this.tableRadio
// console.log(row)
axios.get('/api/download', {
params: {
reportRuleId: row.reportRuleId
}
}).then(response => {
console.log(response.data);
}).catch(error => { this.$message.error(error) })
}
一直使用的是axios.get()这种请求方式,可以访问后台,但是返回的是一堆乱码
3.(更正版)用axios({})这种方式,配置参数
axios({
method: 'GET',
url: '/api/download',
params: {
reportRuleId: row.reportRuleId
},
responseType: 'blob'
}).then(response => {
let blob = new Blob([response.data], {type: 'application/zip'})
let url = window.URL.createObjectURL(blob)
window.location.href = url
}).catch(error => this.$message.error(error) )
这样就可以成功下载到.zip文件
4.(补充)重命名下载的文件名
axios({
method: 'GET',
url: '/api/download',
params: {
reportRuleId: row.reportRuleId
},
responseType: 'blob'
}).then(response => {
let blob = new Blob([response.data], {type: 'application/zip'})
let url = window.URL.createObjectURL(blob)
const link = document.createElement('a') // 创建a标签
link.href = url
link.download = '清单文件' // 重命名文件
link.click()
URL.revokeObjectURL(url) // 释放内存
}).catch(error => this.$message.error(error) )
type:'application/zip'可以更改下载文件的类型,具体有以下这些类型
'doc' => 'application/msword',
'bin' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'so' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'xls' => 'application/vnd.ms-excel',
'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',