上代码!!!
HTML标签代码部分:
<el-upload
class="upload-demo"
accept=".jpg,.JPG,.png,.PNG"
action="#"
:headers="{ 'Justech-Auth': token }"
:multiple="true"
:auto-upload="true"
:limit="5"
:http-request="uploadFile1"
:on-exceed="handleExceed"
:on-preview="downFile"
:on-remove="fileRemove"
:before-upload="beforefileListUpload"
:show-file-list="true"
:file-list="newFileList">
<el-button slot="trigger" size="small" type="primary" style="margin-right: 10px" :loading="uploadLoadingBtn">选择文件</el-button>
</el-upload>
<div style="color: red;margin-left: 15px;">* 支持jpg/png格式,最多上传5个文件</div>
js部分:
data() {
return {
uploadLoadingBtn: false,
token: '',
newFileList: [],// 上传附件集合
}
},
methods: {
handleExceed(files, fileList) {
this.$message.warning('最多上传5个文件!');
},
// 上传之前
beforefileListUpload(file){
let obj = {
id:new Date(),
name: file.name,
isSuccess: false,
file:file
}
// this.newFileList.push(obj)
},
// 上传方法
uploadFile1(item) {
this.uploadLoadingBtn = true;
let formData = new FormData();
formData.append("files", item.file)
api.url(formData).then((res) => {
this.$message.success('上传成功!')
this.uploadLoadingBtn = false;
let obj = {
id: res.data.data,
name: item.file.name,
file: item.file,
uid: item.file.uid,
}
this.newFileList.push(obj)
}).catch(() => {
this.$message.error('上传失败!')
// console.log(this.fileList,'上传失败结果');
})
},
// 删除附件
fileRemove(file, fileList) {
this.newFileList = fileList;
console.log(fileList,'fileLis3333333');
},
// 下载
filePreview(file){
if(file.url != undefined){
// 假设文件 URL 为 fileUrl,文件名为 fileName
const fileUrl = file.url;
const fileName = file.fileName;
// 创建一个 <a> 标签
const link = document.createElement('a');
link.href = fileUrl;
// link.download = fileName; // 设置下载的文件名
link.setAttribute('download', fileName); // 设置下载的文件名
// 将该 <a> 标签添加到页面上并模拟点击
document.body.appendChild(link);
link.click();
// 清理
document.body.removeChild(link);
}
},
}
至此完成!!!
测试有效!!!感谢支持!!!
本文详细介绍了如何在Vue项目中使用ElementUI的el-upload组件实现文件上传功能,包括设置上传限制、上传前处理、上传方法以及错误和成功提示。
1957

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



