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);
}
},
需要的話可以自己試試,走你~