一.下载
方法一
export function downloadObj({ name= '', key = '' }) {
return request({
url: 'url',
method: 'get',
responseType: 'blob',//请求返回的文件流转为blob
});
}
主要利用a标签的download属性进行下载
export function downloadFile(data,fileName) {
const url = window.URL.createObjectURL(data);
//如果传过来的data不是blob类型,可以通过Blob的构造函数创建Blob对象: data = new Blob([data])
const fileLink= document.createElement('a');
fileLink.style.display = 'none';
fileLink.href = url;
//设置下载时的文件名字
fileLink.setAttribute('download', fileName);
document.body.appendChild(fileLink);
fileLink.click();
document.body.removeChild(fileLink);
}
页面上调用接口及方法即可实现下载
const res=await downloadObj({name:name,key:key});
await downloadFile(res,row.objectKey);
方法二
export function downloadObj(){
return 'URL'
}
//处理url,拼接query上的参数
//encodeURIComponent-->把字符串作为 URI 组件进行编码。
export function handleUrl(url, params) {
for (const i in params) {
if (url.includes('?')) {
url += '&' + i + '=' + encodeURIComponent(params[i])
} else {
url += '?' + i + '=' + encodeURIComponent(params[i])
}
}
return url
}
//拼接url多选参数
//eg:id:['1','2','3']
//拼接好的格式:url?id='1'&id='2'&id='3'
export function handleUrlIds(url, id, idName) {
let _url = JSON.parse(JSON.stringify(url))
if (id && id.length > 0) {
ids.forEach(item => {
if (_url.includes('?')) {
_url += '&' + idName+ '=' + encodeURIComponent(item)
} else {
_url += '?' + idName+ '=' + encodeURIComponent(item)
}
})
}
return _url
}
//模拟a标签点击下载
export function clickDownload(url) {
if (url) {
// 判断浏览器类型
if (navigator.userAgent.indexOf('Firefox') > 0) {
window.location.href = url
} else {
const a = document.createElement('a')
a.href = url
a.click()
}
}
}
let url = handleUrl(downloadObjects(),{...this.params})
url = handleUrlIds(url,selectedId,'id')
clickDownload(url)
二.结合element的upload实现自定义上传文件
页面组件使用
使用了http-request覆盖了默认的上传行为,实现自定义上传
<el-upload
class="upload-demo"
action="#"
:http-request="uploadAction"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
>
<el-button
size="small"
type="primary"
icon="el-icon-upload2"
>文件上传</el-button>
</el-upload>
async uploadAction(param){
const formdata = new FormData();
formdata.append('file', param.file);
//调用接口方法uploadObjects实现上传,this.data为参数
const res=await uploadObjects(formdata,this.data);
},

3564

被折叠的 条评论
为什么被折叠?



