vue+el-upload实现多文件动态上传

vue+el-upload多文件动态上传,供大家参考,具体内容如下

使用场景

点击【添加/删除】,可动态增加/删除行数,并为每行上传附件,附件暂存前端,点击【上传】可以将所有附件和部分名称同时提交后台,实现表格的动态多文件上传。其中el-upload ,相关钩子函数可查看el-upload 官方文档

这里的表格行的新增是在弹框中填完再写入的,也可直接在表格中添加行,然后填写内容(template slot-scope=“scope” 注释部分代码),这里仅提供思路

代码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">取 消</el-button>
                    <el-button type="primary" @click="addFileDetail">确 定</el-button>
                </div>
            </el-dialog>
</div>

js部分代码

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 = '';
            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,1)
                }
            }
        },
        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();
            }
            // 处理以字符串形式上传的关联数据信息
            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();
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot+Vue.js实现前后端分离的文件上传功能

    这篇文章需要一定Vue和SpringBoot的知识,分为两个项目,一个是前端Vue项目,一个是后端SpringBoot项目. 后端项目搭建 我使用的是SpringBoot1.5.10+JDK8+IDEA 使用IDEA新建一个SpringBoot项目,一直点next即可 项目创建成功后,maven的pom配置如下 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> &l

  • vue vantUI实现文件(图片、文档、视频、音频)上传(多文件)

    说在前面 网上有很多种文件上传的方法,根据公司最近的业务需求,要求实现多种文件的上传,在实现过程中,查阅了很多资料,最后,终于把功能实现了,开心! <template> <div> <v-header :left-text="`上传${columnName}`"></v-header> <div class="upload"> <div v-if="columnName === '视频'&q

  • vue中实现上传文件给后台实例详解

    FormData 对象的使用: 1.用一些键值对来模拟一系列表单控件:即把form中所有表单元素的name与value组装成 一个queryString 2. 异步上传二进制文件. (ps:说白了就是不使用form表单实现form表单提交数据或文件,如果还是不懂,请自行百度) 实现过程 1.使用type类型为file的input框实现选择文件(顺便记录一下修改input框的默认样式) 2.修改input框的默认样式 3.通过选择文件拿到数据 4.请求接口 以上就是本次关于vue中实现上传文件给后

  • vue使用axios上传文件(FormData)的方法

    在此主要介绍 如何使用 formData 对象上传单文件和多文件,FormData 就是 XMLHttpRequest Level 2 新增的一个对象,利用它来提交表单.模拟表单提交,当然最大的优势就是可以上传二进制文件. 过多介绍不说,过多的煽情语句不说,直接来来干活,希望对广大博友有所帮助.也希望各位大神不吝赐教 1.前台上传文件的表单和响应函数 <!--文件上传表单--> <form> <input type="text" value="&

  • vue项目中使用axios上传图片等文件操作

    axios 简介 axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征: 从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持 Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止 CSRF/XSRF 首先安装axios: 1.利用npm安装npm install axios –save 2.利用bower安装bower install axios

  • vue实现文件上传功能

    vue 文件上传,供大家参考,具体内容如下 首先 先说一下想要实现的效果 就如截图所见,需要将企业和需要上传的文件提交到后台处理,那么接下来就说如何实现 vue 实现 vue 页面代码 <el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="fileList" :before-upload

  • vue使用axios实现文件上传进度的实时更新详解

    axios 简介 axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征: 从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持 Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止 CSRF/XSRF 引入方式: $ npm install axios //使用淘宝源 $ cnpm install axios //或者使用cdn: <script s

  • vue实现Excel文件的上传与下载功能的两种方式

    一.前言项目中使用到比较多的关于Excel的前端上传与下载,整理出来,以便后续使用或分析他人. 1.前端vue:模板下载与导入Excel 导入Excel封装了子组件,点击导入按钮可调用子组件,打开文件上传的对话框,上传成功后返回结果 <el-col style="padding: 10px 0 20px;"> <el-button class="pull-right" icon="el-icon-upload" type=&qu

  • vue中使用input[type="file"]实现文件上传功能

    注意:input[type="file"] 标签中的属性accept="application/msword,application/pdf" 在pc上正常,但是在手机ios和android上这个文件格式限制会被忽略,所以需要在js中增加格式的判断,以及对应显示样式的设置.(我也是刚发现,如果有遇到这个问题的可以参考下---下面有更改:) ``` <template> <div id="my-careers"> <h

  • Vue axios 中提交表单数据(含上传文件)

    我们经常使用表单来上传数据,以及上传文件,那么怎么在表单提交成功的时候接受服务器的响应,并作出相应操作. 当然使用一般jQuery上传对象的格式也是可以的,如果使用传统的表单上传呢? <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport

随机推荐