vue 多檔案上傳
在這裡我來介紹一下,如何用vue 的 element-ui元件批量上傳檔案。這個官方文檔上沒有直接的參考案例,我是通過在網上看了好多文章終結出來的,希望有遇到和我相同問題的朋友能少走彎路。
官方手冊
連結: element-ui檔案上傳手冊
通過 slot 你可以傳入自定義的上傳按鈕類型和文字提示。可通過設定limit和on-exceed來限制上傳檔案的個數和定義超出限制時的行為。可通過設定before-remove來阻止檔案移除操作。
下為案例圖

<div style="margin-top:-15px">
<el-form-item label="" prop="content">
//el-upload 我這裡是自動送出,先是一張一張的自動上傳到圖檔雲伺服器,然後通過擷取傳回值清單在統一送出到背景伺服器儲存
<el-upload
class="upload-demo"
action="/index.php/Admin/Tools/fileupload" //這個是圖檔上傳位址 背景預設接收是 file
:on-preview="handlePreview" //點選檔案清單中已上傳的檔案時會觸發 handlePreview 方法
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-remove="beforeRemove"
multiple //是否支援多選檔案
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">點選上傳</el-button>
<div slot="tip" class="el-upload__tip">隻能上傳jpg/png檔案,且不超過500kb</div>
</el-upload>
</el-form-item>
<!-- 點選事件按鈕 -->
<el-form-item>
<el-button type="primary" @click="onSubmit" :loading="on_submit">立即送出</el-button>
<el-button style="margin-left:20px" @click="$emit('submit_close')">取消</el-button>
</el-form-item>
</div>
<script>
export default {
data() {
return {
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}], //已上傳的檔案的預設值,我想一般用不到
list:[], //定義儲存上傳資料的 list
form: { //設定form表單的參數 預設為空
publisher_id: null,
lecture_id: this.lecture_id,
type: 'text',
content: null
},
pictureContent:null
};
}, computed: {
//驗證規則
rules() {
let _rules = {
publisher_id: [{required: true, message: '請選擇發送人', trigger: 'change'}],
content: [{required: true, message: '圖檔不能為空', trigger: 'blur'}]
}
return _rules
}
},
methods: {
handleRemove(file,fileList) { //在這裡我強調一下 fileList 和上面的 :file-list="fileList" 沒關系
console.log(file, fileList);
this.list=fileList;
},//圖檔上傳成功
handleSuccess(response,file,fileList) { //file 是剛剛完成上傳的圖檔資訊,fileList 是所有完成上傳的圖檔資訊清單
if (response.code === API_SUCCESS) {
this.list=fileList;
this.pictureContent = response.data.url //調用 pictureContent 設定 content 參數; 設定這個是為了通過驗證
}
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`目前限制選擇 3 個檔案,本次選擇了 ${files.length} 個檔案,共選擇了 ${files.length + fileList.length} 個檔案`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
}
},onSubmit(){
this.$refs.form.validate((valid) => { //點選送出先驗證表單
if (valid) {
let _self = this
_self.form.content=this.list; // 把上傳好的的圖檔參數清單指派給 content
_self.$http.post('/index.php/Admin/Lectures/uploda_msg', _self.form)
.then(({data:{data, code, msg}}) => {
_self.$message({
message: msg,
type: 'success'
})
})
} else {
return false
}
})
},watch: {
pictureContent(val){
this.form['content'] = val //注意:如果有驗證的話這個地方很重要(當圖檔發生改變時form.content為空的話無法通過驗證。這個地方當文本框發生任何變化都會觸發)
},
}
}
</script>