- 发送参数ids长度过长,选择post形式发送请求
- get
- 获取url
buildURL(url, params) { if (!params) { return url } var serializedParams if (isURLSearchParams(params)) { serializedParams = params.toString() } else { var parts = [] forEach(params, function serialize (val, key) { if (val === null || typeof val === 'undefined') { return } if (isArray(val)) { key = key + '[]' } else { val = [val] } forEach(val, function parseValue (v) { if (isDate(v)) { v = v.toISOString() } else if (isObject(v)) { v = JSON.stringify(v) } parts.push(encode(key) + '=' + encode(v)) }) }) serializedParams = parts.join('&') } if (serializedParams) { var hashmarkIndex = url.indexOf('#') if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex) } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams } return url }
- iframe下载文件
downLoadFiles = (srcPath) => { var iframe = document.getElementById('hiddenDownloader') if (iframe === null) { iframe = document.createElement('iframe') iframe.id = 'hiddenDownloader' iframe.style.display = 'none' document.body.appendChild(iframe) } iframe.src = srcPath }
- 调用下载方法
let params = { ids: ids } var srcPath = this.buildURL(`/api/compass/export/history/download`, params) this.downLoadFiles(srcPath)
- 获取url
- post
- axios调用后台API接口获取数据
this.$axios.request({ method:'post', url:'/api//files/filesearch/download', data:{ ids:[ "53ba3fefeb4086a05b805ac9a745a011", "c8ca2aea8ff822f928903522fe7457c3", "fd7baec6fff7e73c1817dcf4743ac2ba", "327dd01cb5351f1fa0537d909b5e9000" ] }, responseType:'arraybuffer'// 下载文件可以打开 }).then((response)=>{ this.download(response.data);// 请求成功回调 ,将获取的下载文件数据返回 }) }
- 创建临时blob的url
let url = window.URL.createObjectURL(new Blob([data]))
- 创建隐藏下载元素,指定href为blob的url
let link = document.createElement('a') // 创建一个超链接 link.style.display = 'none' // 隐藏元素显示 link.href = url // 设置元素路径 link.download = 'download_' + new Date().valueOf() + '.zip' // 下载后文件名 link.click() // 下载文件 document.body.removeChild(link)// 下载完成移除元素 window.URL.revokeObjectURL(url)// 释放掉blob对象
- 完整代码
getDownloadData () { this.$axios.request({ method: 'post', url: '/api//files/filesearch/download', data: { ids: [ '53ba3fefeb4086a05b805ac9a745a011', 'c8ca2aea8ff822f928903522fe7457c3', 'fd7baec6fff7e73c1817dcf4743ac2ba', '327dd01cb5351f1fa0537d909b5e9000' ] }, responseType: 'arraybuffer'// 下载文件可以打开 }).then((response) => { this.download(response.data)// 请求成功回调 ,将获取的下载文件数据返回 }) }, download(data){ if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.download = 'download_' + new Date().valueOf() + '.zip' link.click() document.body.removeChild(link) window.URL.revokeObjectURL(url) }
- axios调用后台API接口获取数据
调用API接口下载文件的两种实现方式GET POST
最新推荐文章于 2024-06-25 14:58:18 发布