1. 程式人生 > 程式設計 >vue+el-upload實現多檔案動態上傳

vue+el-upload實現多檔案動態上傳

+el-upload多檔案動態上傳,供大家參考,具體內容如下

使用場景

點選【新增/刪除】,可動態增加/刪除行數,併為每行上傳附件,附件暫存前端,點選【上傳】可以將所有附件和部分名稱同時提交後臺,實現表格的動態多檔案上傳。其中el-upload ,相關鉤子函式可檢視el-upload 官方文件

這裡的表格行的新增是在彈框中填完再寫入的,也可直接在表格中新增行,然後填寫內容(template slot-scope=“scope” 註釋部分程式碼),這裡僅提供思路

vue+el-upload實現多檔案動態上傳

程式碼html部分

<div class="vue-box">
           <div class="title-line">
                            其他必須持有的證照<el-button type="primary" size="mini" style="height: 20px;padding-top: 3px !important;margin-left: 50px" icon="el-icon-plus" @click="handleAddDetails">新增行</el-button>
                            <el-button type="primary" size="mini" style="height: 20px;padding-top: 3px !important;margin-left: 50px" icon="el-icon-plus" @click="doFileUpload()">上傳</el-button>
            </div>
            <el-table
                    :row-class-name="rowClassNameDeal"
                    :data="tableData"
                    style="width: 100%;">
                <el-table-column
                        prop="id"
                        width="50"
                        label="序號">
                </el-table-column>
                <el-table-column
                        prop="cardName"
                        width="180"
                        label="證照名稱">
                    <!--<template slot-scope="scope">
                        <el-input size="mini" v-model="tableData[scope.row.id-1].cardName"></el-input>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="cardNo"
                        width="180"
                        label="證件號碼">
                    <!--<template slot-scope="scope">
                        <el-input size="mini" v-model="tableData[scope.row.id-1].cardNo"></el-input>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="startDate"
                        width="180"
                        label="起始日期">
                    <!--<template slot-scope="scope">
                        <el-date-picker
                                v-model="tableData[scope.row.id-1].startDate"
                                style="width: 80%;"
                                size="mini"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="選擇日期">
                        </el-date-picker>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="endDate"
                        width="180"
                        label="結束日期">
                    <!--<template slot-scope="scope">
                        <el-date-picker
                                v-model="tableData[scope.row.id-1].endDate"
                                style="width: 80%;"
                                size="mini"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="選擇日期">
                        </el-date-picker>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="address"
                        label="附件">
                    <template slot-scope="scope">
                        <el-upload
                                :ref="scope.row.cardName"
                     
:http-request="dynamicUpload" :before-upload="beforeUploadFile(scope.row)" :on-remove="uploadRemove" :before-remove="uploadBeforeRemove" :on-preview="uploadPreview" name="upload" :limit="1" :data="scope.row.cardName" :on-exceed="uploadHandleExceed" :file-list="tableData[scope.row.id-1].fileUploadedList"> <el-button size="mini" type="info">點選上傳</el-button> </el-upload> </template> </el-table-column> <el-table-column prop="date" width="80" label="操作"> <template slot-scope="scope"> <el-button size="mini" type="warning" @click="handleDeleteDetails(scope.row)">刪除</el-button> </template> </el-table-column> </el-table> <el-dialog title="證照資訊" :visible.sync="addCardVisible" width="40%"> <el-form :model="fileInfo"> <el-form-item label="證照名稱" :label-width="labelWidth"> <el-input v-model="fileInfo.cardName" autocomplete="off" style="width: 100%;"></el-input> </el-form-item> <el-form-item label="證件號碼" :label-width="labelWidth"> <el-input v-model="fileInfo.cardNo" autocomplete="off" style="width: 100%;"></el-input> </el-form-item> <el-form-item label="生效日期" :label-width="labelWidth"> <el-date-picker type="date" placeholder="生效日期" value-format="yyyy-MM-dd" v-model="fileInfo.startDate" style="width: 100%;"></el-date-picker> </el-form-item> <el-form-item label="失效日期" :label-width="labelWidth"> <el-date-picker type="date" placeholder="失效日期" value-format="yyyy-MM-dd" v-model="fileInfo.endDate" style="width: 100%;"></el-date-picker> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="addCardVisible = false">取 消</elwww.cppcns.com
-button> <el-button type="primary" @click="addFileDetail">確 定</el-button> </div> </el-dialog> </div>

部分程式碼

let nodeVue = new Vue({
    el: '.vue-box',data: {
        labelWidth: '150px',tableData: [],uploadParams:{
            fileTagName: ''
        },totalFileList:[],totalFileNameList:[],addCardVisible:false,fileInfo:{
            cardName:'',cardNo:'',startDate:'',endDate:''
        }
    },methods:{
        // 檔案相關
        uploadRemove:function(file) {
            let that = this;
            // 刪除檔案列表中的檔案
            for(let i=0;i<that.totalFileNameList.length;i++){
                if(that.totalFileNameList[i].fileName === file.name){
                    that.totalFileNameList.splice(i,1)
                }
            }
            for(let i=0;i<that.totalFileList.length;i++){
                if(that.totalFileList[i].name === file.name){
                    that.totalFileList.splice(i,1)
                }
            }
        },// 上傳檔案引數設定
        beforeUploadFile:function(row) {
            console.log(row.cardName);
            this.uploadParams.fileTagName=row.cardName
            this.uploadParams.fid=row.id
        },// 下載檔案,點選檔案列表中的檔案下載
        uploadPreview:function(file){
            console.log(file);
        },uploadHandleExceed:function(files,fileList) {
            this.$message.warning(`當前限制選擇 1 個檔案`);
        },uploadBeforeRemove:function(file) {
            return this.$confirm(`確定移除 ${ file.name }?`);
        },// 附件新增行,開啟新增行彈框
        handleAddDetails(){
            let that = this;
            that.addCardVisible = true;
            that.fileInfo.cardName = '';
            that.fileInfo.cardNo = '';
            that.fileInfo.startDate = '';
            that.fileInfo.endDate = '';
        },// 向表格資料中新增一行
        addFileDetail(){
            let that = this;
            if (that.tableData == undefined) {
                that.tableData = new Array();
            }
            let obj = {};
            obj.id = 0;
            obj.cardName = that.fileInfo.cardName;
            obj.cardNo = that.fileInfo.cardNo;
            obj.startDate = that.fileInfo.startDate;
            obj.endDate = that.fileInfo.endDate;
            obj.fileUploadedList=[];
            that.tableData.push(obj);
            that.addCardVisible = false;
        },// 刪除行
        handleDeleteDetails(row){
            let that = this;
            that.tableData.splice(row.id-1,1);
            //同時 刪除檔案列表及關聯列表中的資料
            let tmpFileName = '';
         http://www.cppcns.com
for(let i=0;i<that.totalFileNameList.length;i++){ if(that.totalFileNameList[i].cardName === row.cardName){ tmpFileName = that.totalFileNameList[i].fileName;// 先暫存再執行刪除操作 that.totalFileNameList.splice(i,1); } } for(let i=0;i<that.totalFileList.length;i++){ if(that.totalFileList[i].name === tmpFileName){ that.totalFileList.splice(i,rowClassNameDeal({row,rowIndex}) { //把每一行的索引放進row.id,此方法用於生成表格中的序號,當在表格中填寫內容時,每一行都需要繫結不同的v-model row.id = rowIndex+1; },// 自定義上傳,只將檔案暫存在前端 dynamicUpload(content){ let that = this; if(content.data.length === 0){ that.$message.warning(`請填寫證照名稱!!!`); that.$refs[content.data].clearFiles(); return false; } for(let i=0;i<that.totalFileNameList.length;i++){ if(that.totalFileNameList[i].fileName === content.file.name){ that.$message.warning('改檔案已上傳,請重新選擇檔案上傳!!!'); that.$refs[content.data].clearFiles(); return false; } } // 將檔案加入到待傳輸的檔案列表 that.totalFileList.push(content.file) let fileNameData = { cardName: content.data,fileName: content.file.name } // totalFileNameList 儲存檔案和表格內容的關聯關係,這裡只關聯了證照名稱 that.totalFileNameList.push(fileNameData) },// 執行上傳操作將檔案和表格資訊一起傳送到後臺 doFileUpload(){ let that = this; if(that.totalFileList.length === 0){ that.$message.warning("請上傳檔案!!!"); return; } // 上傳檔案需要用FormData,processData和contentType 兩個引數必須設定,否則上傳不成功 const params = new FormData(); // 為上傳的每個檔案命名,方便後臺獲取時與表格資料關聯 for (let i = 0; i < that.totalFileList.length; i++) { params.append(that.totalFileList[i].name,that.totalFileList[i]); } params.append("fileNameList",JSON.stringify(that.totalFileNameList)); $.ajax({ url:baseurl+"/testupload/fileUpload",type:"POST",dataType: "json",processData: false,//用於對data引數進行序列化處理 這裡必須false contentType: false,//必須 data:params,success:function(res){ that.$message.warning('上傳成功'); } }); } },created: function(){ } })

後臺接收程式碼

@Controller
@RequestMapping("/testupload")
public class RegisterController {

 // 附件從 request中獲取
    @RequestMapping("/fileUpload")
    @ResponseBody
    public ServerResponse fileupload(HttpServletRequest request,String fileNameList){
        try{
            if(fileNameList == null){
                throw new Exception("請選擇檔案後上傳!!!");
            }
            // 1. 上傳的位置
            String path = "E:\\uploadfile";
            //判斷該路徑是否存在
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 處理以字串形式上傳的關聯資料資訊
         http://www.cppcns.com   JSONArray jsonArray = JSON.parseArray(fileNameList);
            // 遍歷關聯列表
            for(Object object : jsonArray){
                JSONObject jsonObject = JSON.parseObject(object.toString());
                System.out.println(jsonObject.getString("cardName"));
                // 獲取檔案
                MultipartFile file1 = ((MultipartHttpServletRequest) request).getFile(jsonObject.getString("fileName"));
                // 獲取檔案資訊
                String filename = file1.getOriginalFilename();
                System.out.println(filename);
                // 儲存檔案
                file1.transferTo(new File(path,filename));
            }
        }catch (Exception e) {
            log.error(e.getMessage());
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。