Vue基于element ui中Upload组件实现文件上传下载—实例
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
1.在页面中引入Upload组件
<!--上传文件-->
<el-upload class="upload-demo"
ref="upload"
action="#"
:limit="3"
:show-file-list="true"
:file-list="getFileList(scope.row.fileInfoList|| [])"
:on-exceed="handleExceed"
:on-remove="(...arg) => handleRemove(...arg, scope.row)"
:before-upload="(...arg) => handleBeforeUpload(...arg, scope.row)"
:http-request="(...arg) => uploadFile(...arg, scope.row, scope.$index) ">
<el-button size="small" type="text" >上传文件</el-button>
</el-upload>
<!--文件预览及下载-->
<el-link type="primary" style="margin-right:10px" v-for="item in form.fileInfoList" :key="item.fileId" @click.prevent="downloadFile(item)">{{ item.name }}</el-link>
2.在api中定义fileInfo.js文件,内容如下
//api中fileInfo.js文件
export function uploadFile(data) {
return request({
url: '/test/uploadFile',
method: 'post',
data
})
}
export function downLoad(query) {
return request({
url: '/test/downFile',
method: 'get',
params: query
})
}
3.在methods中添加如下方法
<script>
//界面中调用fileInfo.js文件
import {uploadFile, downLoad} from "@/api/fileInfo";
export default {
methods: {
//格式化文件列表数据
getFileList(row) {
return row.map((item) => {
if (item.fileId) {
item.status = "success";
item.uid = item.fileId;
}
return item;
});
},
//上传前
handleBeforeUpload(file, row) {
const flag = file.size / 1024 / 1024 < 10;
if (!flag) {
this.msgError("上传文件大小不能超过 10MB!");
} else {
const flag = row.fileInfoList.some((item) => {
return item.name == file.name;
});
if (flag) this.msgError("上传文件已存在");
return !flag;
}
return flag;
},
//上传文件
uploadFile(file, row, index) {
let formData = new FormData();
formData.append("file", file.file);
formData.append("uid", file.file.uid);
uploadFile(formData)
.then((res) => {
if (res.code == 200) {
row.fileInfoList = (row.fileInfoList || []).concat(
Object.assign({ name: file.file.name }, res.data)
);
}
//上传文件成功后清空fileList列表缓存
//this.refs.upload.clearFiles();
})
.catch((err) => {
let fileList = this.$refs["upload"].uploadFiles;
fileList.splice(
fileList.findIndex((item) => item.uid == file.file.uid), 1
);
});
},
//删除
handleRemove(file, fileList, row) {
row.fileInfoList = fileList;
},
//限制选择个数
handleExceed(files, fileList) {
this.msgError(
`最多上传 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
files.length + fileList.length
} 个文件`
);
},
//下载文件
downloadFile( row) {
downLoad({ fileName: row.url }).then((res) => {
if (res.code == 200) {
window.open(res.msg);//浏览器中打开新的界面
//window.location.href=url;//原始界面中打开
}
});
}
}
}
</script>
4.关于其它方法使用请查看element官方文档:Element - The world's most popular Vue UI framework
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45
7 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献4条内容
所有评论(0)