# axios 中 GET 下获取流文件下载
自己的项目中下载文件需要后端的权限验证,GET 方式要传 auth 所以不能直接 url 下载。这时候发现后端传回来的流数据无法直接下载。这时候通过修改 axios 的 responseType 来完成文件下载
/**
* 下载文档
* @param {*} data
*/
export function DownDocument(data) {
return request({
url: '/v1/Document/DownDocument',
method: 'get',
data,
headers: {isCheck: true, isGet: true},
responseType: 'blob' # 这个改成blob 这个是关键
})
}
然后 response 返回后将流数据处理下
DownDocument({
src: src,
name: name
}).then(response => {
const href = window.URL.createObjectURL(new Blob([response.data], { type: response.data.type }));
let downloadElement = document.createElement("a");
downloadElement.href = href;
downloadElement.download = name; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放blob对象
});
这样就能通过 axios 来完成文件下载了
# element-ui 中 upload 的多文件上传(不是源码中的一个个上传是一次上传)
在做文档上传的时候发现多文件上传在 element-ui 中是一个一个文件上传的,也就是说多个文件上传会访问多次上传接口对服务器压力会很大,这时候就考虑修改下能一次上传多个文件。经过多次的修改,代码如下
<el-upload
class="upload"
drag
action="1"
multiple
ref="upload"
:limit="maxLimit"
:http-request="addUpload" # 用这个自定义上传来完成
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:on-remove="handleRemove"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div
class="el-upload__tip"
slot="tip"
>最多上传{{maxLimit}}个文件,且单文件不超过{{maxSize}}MB</div>
</el-upload>
addUpload(params) { # 这边自定义上传 就虚拟下实际只是将文件数据放入一个对象中来记录
this.fileList[params.file.uid] = {
file: params.file,
onSuccess: params.onSuccess, # 进度操作 这三个操作很重要
onProgress: params.onProgress, # 成功操作
onError: params.onError, # 失败操作
uid: params.file.uid,
type: 'ready' # 通过这个状态来区分文件类型
}
}
# 然后点击上传后 真正的触发多文件上传
CreateUpload() {
let self = this, formData = new FormData()
for (let i in this.fileList) {
if (this.fileList[i].type == 'ready') {
formData.append('document', this.fileList[i].file)
formData.append('uid', this.fileList[i].uid)
}
}
formData.append('admin_id', util.cookies.get('uuid'))
formData.append('type', 1)
if (formData.get('uid') == null) return this.$message.error('请选择上传文件')
this.loading = true
CreateDocument(formData, this.handelProgress)
.then(async res => {
res.map(i => {
if (i.res == 1) {
this.fileList[i.uid].onSuccess()
this.fileList[i.uid].type = 'success'
}
if (i.res == 2) {
this.fileList[i.uid].onError()
this.fileList[i.uid].type = 'error'
}
})
this.loading = false
})
.catch(() => {
this.loading = false
})
}
/**
* 上传文档
* @param {*} data
*/
export function CreateDocument(data, progressEvent) {
return request({
url: '/v1/Document/CreateDocument',
method: 'post',
data,
headers: { 'content-type': 'multipart/form-data', isCheck: true },
onUploadProgress: res => {
# 这边传入进度的回调函数 返回进度来显示文件上传进度
const percentCompleted = Math.floor((res.loaded * 100) / res.total)
progressEvent({ percent: percentCompleted })
}
})
}
具体代码 upload(上传) 这边唯一没办法的就是 进度显示是总的进度没办法每个文件单独区分的进度
← 2019-12-06 2019-12-23 →