在elementui 的上傳組件中實現單文件上傳,使用:limit="1" 屬性限制選擇文件個數,有個弊端就是當選擇完一個文件之后就不能再繼續選擇文件,這並不是產品經理想要的,我們期望的結果是:當再次選擇時直接覆蓋上次上傳的文件,保證文件列表中只有一個文件。
- accept屬性可以限制文件類型,file-list是文件列表,action綁定文件上傳路徑
- 當手動提交文件時,使用this.$refs.upload.submit()來上傳文件
- 選擇文件可以觸發鈎子函數on-change,因此在on-change鈎子函數中去操作。
//組件
<el-upload class="upload_wrap" ref="upload" action="uploadUrl" accept=".png" :auto-upload="false"
:file-list="fileList" :on-progress="onProgress" :on-change="onChange">
<el-button slot="trigger" type="text"><i class="el-icon-upload" style="font-size:16px"></i>上傳文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
<div slot="tip" class="el-upload__tip">只支持上傳.h5文件,文件最大不得超過2G</div>
</el-upload>
//方法
// 限制文件上傳的個數
onChange(file, list) {
if (list.length > 1 && file.status !== "fail") {
list.splice(0, 1);
} else if (file.status === "fail") {
errorMsg("上傳失敗,請重新上傳!");
list.splice(0, 1);
}
},
// 上傳之前限制文件格式
beforeUp(file) {
const isH5 = file.name.split(".")[1] === "png";
const isLt2G = file.size / 1024 / 1024 / 1024 < 2;
if (!isH5) {
errorMsg("僅支持上傳.png文件");
}
if (!isLt2G) {
errorMsg("上傳文件大小不能超過 2G!");
}
return isH5 && isLt2G;
},
submitUpload() {
this.$refs.upload.submit();
},
//樣式,去掉過渡動畫
.upload_wrap {
display: flex;
flex-direction: column;
align-items: flex-start;
}
/deep/ .el-list-enter-active,
/deep/ .el-list-leave-active {
transition: none;
}
/deep/ .el-list-enter,
/deep/ .el-list-leave-active {
opacity: 0;
}
/deep/ .el-upload-list__item-name {
width: 300px;
}
/deep/ .el-upload-list {
height: 40px;
}