vue+el-upload realizes dynamic upload of multiple files

vue+el-upload realizes dynamic upload of multiple files

vue+el-upload multiple files dynamic upload, for your reference, the specific content is as follows

Usage scenarios

Click [Add/Delete] to dynamically increase/delete the number of rows and upload attachments for each row. The attachments are temporarily stored on the front end. Click [Upload] to submit all attachments and partial names to the background at the same time, realizing dynamic multi-file uploading of the table. For el-upload and related hook functions, please refer to the official documentation of el-upload.

The new table rows here are added after filling in the pop-up box, or you can add rows directly to the table and fill in the content (template slot-scope="scope" comment part of the code). Here is just a thought

Code html part

<div class="vue-box">
           <div class="title-line">
                            Other required certificates<el-button type="primary" size="mini" style="height: 20px;padding-top: 3px !important;margin-left: 50px" icon="el-icon-plus" @click="handleAddDetails">Add row</el-button>
                            <el-button type="primary" size="mini" style="height: 20px;padding-top: 3px !important;margin-left: 50px" icon="el-icon-plus" @click="doFileUpload()">Upload</el-button>
            </div>
            <el-table
                    :row-class-name="rowClassNameDeal"
                    :data="tableData"
                    style="width: 100%;">
                <el-table-column
                        prop="id"
                        width="50"
                        label="Serial number">
                </el-table-column>
                <el-table-column
                        prop="cardName"
                        width="180"
                        label="Certificate Name">
                    <!--<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="ID number">
                    <!--<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="Start Date">
                    <!--<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="Select a date">
                        </el-date-picker>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="endDate"
                        width="180"
                        label="End Date">
                    <!--<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="Select a date">
                        </el-date-picker>
                    </template>-->
                </el-table-column>
                <el-table-column
                        prop="address"
                        label="Attachment">
                    <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">Click to upload</el-button>
                        </el-upload>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="date"
                        width="80"
                        label="Action">
                    <template slot-scope="scope">
                        <el-button size="mini" type="warning" @click="handleDeleteDetails(scope.row)">Delete</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <el-dialog title="Certificate Information" :visible.sync="addCardVisible" width="40%">
                <el-form :model="fileInfo">
                    <el-form-item label="Certificate Name" :label-width="labelWidth">
                        <el-input v-model="fileInfo.cardName" autocomplete="off" style="width: 100%;"></el-input>
                    </el-form-item>
                    <el-form-item label="ID number" :label-width="labelWidth">
                        <el-input v-model="fileInfo.cardNo" autocomplete="off" style="width: 100%;"></el-input>
                    </el-form-item>
                    <el-form-item label="Effective Date" :label-width="labelWidth">
                        <el-date-picker type="date" placeholder="Effective date" value-format="yyyy-MM-dd" v-model="fileInfo.startDate" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="Expiration Date" :label-width="labelWidth">
                        <el-date-picker type="date" placeholder="Expiration date" 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">Cancel</el-button>
                    <el-button type="primary" @click="addFileDetail">OK</el-button>
                </div>
            </el-dialog>
</div>

js part of the code

let nodeVue = new Vue({
    el: '.vue-box',
    data: {
        labelWidth: '150px',
        tableData: [],
        uploadParams:{
            fileTagName: ''
        },
        totalFileList:[],
        totalFileNameList:[],
        addCardVisible:false,
        fileInfo:{
            cardName:'',
            cardNo:'',
            startDate:'',
            endDate:''
        }
    },
    methods:{
        // File related uploadRemove:function(file) {
            let that = this;
            // Delete files in the file list 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)
                }
            }
        },
        // Upload file parameter settings beforeUploadFile:function(row) {
            console.log(row.cardName);
            this.uploadParams.fileTagName=row.cardName
            this.uploadParams.fid=row.id
        },
        // Download files, click on the file in the file list to download uploadPreview:function(file){
            console.log(file);
        },
        uploadHandleExceed:function(files, fileList) {
            this.$message.warning(`Currently limited to 1 file selection`);
        },
        uploadBeforeRemove:function(file) {
            return this.$confirm(`Are you sure you want to remove ${ file.name }?`);
        },
        // Add an attachment row, open the add row pop-up window handleAddDetails(){
            let that = this;
            that.addCardVisible = true;
            that.fileInfo.cardName = '';
            that.fileInfo.cardNo = '';
            that.fileInfo.startDate = '';
            that.fileInfo.endDate = '';
        },
        // Add a row to the table data 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;
        },
        // Delete row handleDeleteDetails(row){
            let that = this;
            that.tableData.splice(row.id-1, 1);
            // Delete the data in the file list and the associated list at the same time let tmpFileName = '';
            for(let i=0;i<that.totalFileNameList.length;i++){
                if (that.totalFileNameList[i].cardName === row.cardName) {
                    tmpFileName = that.totalFileNameList[i].fileName; // Temporarily save and then delete that.totalFileNameList.splice(i,1);
                }
            }
            for(let i=0;i<that.totalFileList.length;i++){
                if (that.totalFileList[i].name === tmpFileName) {
                    that.totalFileList.splice(i,1)
                }
            }
        },
        rowClassNameDeal({row, rowIndex}) { 
            //Put the index of each row into row.id. This method is used to generate the serial number in the table. When filling in the content in the table, each row needs to be bound to a different v-model
            row.id = rowIndex+1;
        },
        // Custom upload, only temporarily store the file in the front end dynamicUpload(content){
            let that = this;
            if(content.data.length === 0){
                that.$message.warning(`Please fill in the name of the certificate!!!`);
                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('The file has been uploaded, please reselect the file to upload!!!');
                    that.$refs[content.data].clearFiles();
                    return false;
                }
            }
            // Add the file to the list of files to be transferred that.totalFileList.push(content.file)
            let fileNameData = {
                cardName: content.data,
                fileName: content.file.name
            }
            // totalFileNameList stores the relationship between files and table contents. Here, only the license name is associated that.totalFileNameList.push(fileNameData)
        },
        // Execute the upload operation and send the file and table information to the background doFileUpload(){
            let that = this;
            if (that.totalFileList.length === 0) {
                that.$message.warning("Please upload the file!!!");
                return;
            }
            // To upload a file, you need to use FormData. The processData and contentType parameters must be set, otherwise the upload will fail const params = new FormData();
            // Name each uploaded file to facilitate the association with table data when backend gets it 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, //Used to serialize the data parameter. This must be false.
                contentType: false, //Required data:params,
                success:function(res){
                    that.$message.warning('Upload successful');
                }
            });
        }
    },
    created: function(){       
    }
})

Backend receiving code

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

 // The attachment is obtained from the request @RequestMapping("/fileUpload")
    @ResponseBody
    public ServerResponse fileupload(HttpServletRequest request,String fileNameList){
        try{
            if(fileNameList == null){
                throw new Exception("Please select the file before uploading!!!");
            }
            // 1. Upload location String path = "E:\\uploadfile";
            //Judge whether the path exists File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            // Process the associated data information uploaded in string form JSONArray jsonArray = JSON.parseArray(fileNameList);
            // Traverse the association list for(Object object : jsonArray){
                JSONObject jsonObject = JSON.parseObject(object.toString());
                System.out.println(jsonObject.getString("cardName"));
                // Get file MultipartFile file1 = ((MultipartHttpServletRequest) request).getFile(jsonObject.getString("fileName"));
                // Get file information String filename = file1.getOriginalFilename();
                System.out.println(filename);
                // Save file file1.transferTo(new File(path, filename));
            }
        }catch (Exception e) {
            log.error(e.getMessage());
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementation of uploading multiple files at once with el-upload in element-ui
  • vue+element_ui uploads files and passes additional parameters
  • el-upload http-request uses multiple file uploads with other parameters

<<:  Introduction to MySQL <> and <=> operators

>>:  How to get the size of a Linux system directory using the du command

Recommend

Tomcat class loader implementation method and example code

Tomcat defines multiple ClassLoaders internally s...

How to use webpack and rollup to package component libraries

Preface I made a loading style component before. ...

How to start tomcat using jsvc (run as a normal user)

Introduction to jsvc In production, Tomcat should...

CSS specification BEM CSS and OOCSS sample code detailed explanation

Preface During project development, due to differ...

Count the list tags in HTML

1. <dl> defines a list, <dt> defines ...

Deleting files with spaces in Linux (not directories)

In our daily work, we often come into contact wit...

A brief discussion on Axios's solution to remove duplicate requests

Table of contents 1. Cancel duplicate requests 2....

Docker installation and configuration steps for MySQL

Table of contents Preface environment Install Cre...

How to set Tomcat as an automatically started service? The quickest way

Set Tomcat to automatically start the service: I ...

js implements form validation function

This article example shares the specific code of ...

HTTP Status Codes

This status code provides information about the s...

js realizes the image cutting function

This article example shares the specific code of ...

Detailed example of deploying Nginx+Apache dynamic and static separation

Introduction to Nginx dynamic and static separati...