elementUI里面文件上传已经写好,挺好用的,不过我今天遇到一个情况,花了我一点时间,所以还是在这里记录一下,也许你也会遇到这种情况,那就刚好可以看看。
需求:点击上传一个图片或者PDF文件,只是假上传,在最后提交的时候才真正的上传,并且将上传的文件放到最后提交的接口中,并支持预览,下载,删除功能。
官方给了上传头像的例子:
// 官方上传头像
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:on-success="handleSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
// 官方上传文件例子
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-change="handleChange"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
零零碎碎的都有讲,但是又没有讲全,选择之后文件是什么样子?存在哪里?等等,需求最后实现的方式:
// html部分
<el-upload
ref="upload"
action="#"
list-type="picture-card"
:multiple="true"
accept="image/jpeg, image/png, application/pdf"
:file-list="fileList"
:auto-upload="false"
:before-upload="beforeUpload"
:on-change="selectFile"
:disabled="fileList.length > 0">
<div class="el-upload__tip" slot="tip">点击上传 PDF,JPG 格式文件,文件大小不超过10M</div>
<i class="el-icon-plus"></i>
<div class="el-upload__text">上传文件</div>
<div slot="file" slot-scope="{file}">
<img class="el-upload-list__item-thumbnail" :src="file.url" alt />
<span class="el-upload-list__item-actions">
<span
style="margin-top:10px"
class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)">
<i class="el-icon-zoom-in"></i>
</span>
<span class="el-upload-list__item-download" @click="handleDownload(file)">
<i class="el-icon-download"></i>
</span>
<span
class="el-upload-list__item-delete"
@click="handleRemove(file)">
<i class="el-icon-delete"></i>
</span>
<span style="font-size:12px;">{{file.name}}</span>
</span>
</div>
</el-upload>
// js部分
const acceptTypes = ["image/jpeg", "image/jpg", "image/png"];
selectFile(file) {
this.fileList.push(file);
},
beforeUpload(file) {
let fileTypes = ["application/pdf"];
const isJPG = acceptTypes.includes(file.type);
const isLt10M = file.size / 1024 / 1024 < 10;
const isPDF = fileTypes.includes(file.type);
if (!isJPG && !isPDF) {
this.$message.error("文件必须是PDF格式或者图片格式");
}
if (!isLt10M) {
this.$message.error("图片大小不超过10M!");
}
return (isPDF || isJPG) && isLt10M;
},
handlePictureCardPreview(file) {
if (acceptTypes.includes(file.raw.type)) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
} else {
this.fileDialogVisible = true;
this.fileUrl = pdf.createLoadingTask(file.url);
}
},
handleRemove(file, fileList) {
this.$store.dispatch("selectElectricMeter", {
file: ""
});
this.originForm.file = "";
},
handleDownload(file) {
if (acceptTypes.includes(file.raw.type)) {
var link = document.createElement("a");
link.download = file.name;
link.href = file.url;
link.click();
} else {
window.open(file.url);
}
},
需要的话可以自己试试,走你~