ELEMENT-UI實現多檔案加表單引數上傳
阿新 • • 發佈:2019-02-15
element-ui是分圖片多次上傳,一次上傳一個圖片。
如果想一次上傳多個圖片,就得關掉自動上傳:auto-upload=‘false’,同時不使用element內建上傳函式,換成自己寫的onsubmit()
為了實現圖片的新增刪除,可在on-change與on-remove事件中取得filelist(filelist實質就是uploadFiles的別名,而uploadFiles就是element內建的用於儲存待上傳檔案或圖片的陣列),在最後一步提交的過程中,將filelist中的值一一新增到formdata物件中(formdata.append()新增,formdata.delete()刪除),然後統一上傳。
ps:on-preview事件和<el-dialog>元件以及對應屬性、方法這一體系是用來實現圖片的點選放大功能。 被註釋掉的beforeupload只有一個實參,是針對單一檔案上傳時使用到的,這裡無法用上
<template> <div> <el-upload action="http://127.0.0.1:8000/api/UploadFile/" list-type="picture-card" :auto-upload="false" :on-change="OnChange" :on-remove="OnRemove" :on-preview="handlePictureCardPreview" :before-remove="beforeRemove" > <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> <el-button type="" @click="fun">點選檢視filelist</el-button> <el-button type="" @click="onSubmit">提交</el-button> </div> </template> <script> import {host,batchTagInfo} from '../../api/api' export default { data() { return { param: new FormData(), form:{}, count:0, fileList:[], dialogVisible:false, dialogImageUrl:'' }; }, methods: { handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, beforeRemove(file, fileList) { return this.$confirm(`確定移除 ${ file.name }?`); }, OnChange(file,fileList){ this.fileList=fileList }, OnRemove(file,fileList){ this.fileList=fileList }, //阻止upload的自己上傳,進行再操作 // beforeupload(file) { // console.log('-------------------------') // console.log(file); // //建立臨時的路徑來展示圖片 // //重新寫一個表單上傳的方法 // this.param = new FormData(); // this.param.append('file[]', file, file.name); // this.form={ // a:1, // b:2, // c:3 // } // // this.param.append('file[]', file, file.name); // this.param.append('form',form) // return true; // }, fun(){ console.log('------------------------') console.log(this.fileList) }, onSubmit(){ this.form={ a:1, b:2, c:3 } let file='' for(let x in this.form){ this.param.append(x,this.form[x]) } for(let i=0;i<this.fileList.length;i++){ file='file'+this.count this.count++ this.param.append(file,this.fileList[i].raw) } batchTagInfo(this.param) .then(res=>{ alert(res) }) } } } </script> <style> </style>