使用springboot+vue+elementui+axios上传多个文件

声明:本项目使用的是vue脚手架+elementui

脚手架创建项目(vue init webpack 项目名)

引入element-ui

npm i element-ui -S

在main.js中添加

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

添加axios

npm install axios --save-dev

在main.js添加下面代码   

import axios from 'axios';
​​
​​axios.defaults.baseURL = "http://localhost:8080/"; // 关键步骤–填写后台请求统一的地址 这两段代码就是让后面请求后台时不用重复写地址
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

Vue.prototype.$http=axios;

 

前端html代码:把这个div

<div>
    <div style="text-align: left">
      <el-button type="success" @click="to"> 返回</el-button>
    </div>
    <el-form :model="formValue" :rules="rules" ref="formValue" label-width="100px" class="demo-formValue">
      <el-form-item label="中文名称" prop="cnName">
        <el-input v-model="formValue.cnName"></el-input>
      </el-form-item>
      <el-form-item label="英文名称" prop="enName">
        <el-input v-model="formValue.enName"></el-input>
      </el-form-item>


      <el-form-item ref="upload_attach_item_iamge" label="展示图片" prop="image" size='small' v-if="!isUpdate">
        <el-upload style="float: left"

                   :drag="true"
                   ref="upload_attach"
                   class="upload-demo"
                   action=""
                   multiple
                   accept=".jpg,.png,.jpeg"
                   :limit="4"
                   :on-change="changFileImage"
                   :on-exceed="handleExceed"
                   :on-remove="removeImageFile"
                   :file-list="imageFileList"
                   :auto-upload="false"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <!--          <div style="width:5vh;margin-top: 5px">-->
          <!--            <el-image v-if=isUpdate  fit="fill" :src="formValue.imagePath" :preview-src-list="srcList" ></el-image>-->
          <!--          </div>-->

          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>
        <el-progress :percentage="progressPercent" v-show="show_progress"></el-progress>

      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="submitForm('formValue')" v-if="!isUpdate">{{buttonTitle}}</el-button>
        <el-button type="primary" @click="updateExhibits()" v-if="isUpdate">{{buttonTitle}}</el-button>
        <el-button @click="resetForm('formValue')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

前端js代码 

import loading from "../../../loading";

  export default {
    name: "CaseTypeManager",
    data() {
      return {
        formValue: {
          id: 0,
          cnName: "",
          enName: "",
          image: ""
        },
        isUpdate: false,
        imageFileList: [],
        //上传文件进度条
        progressPercent: 0,
        show_progress: false,

        buttonTitle : "创建",

        rules:{
          cnName: [
            {required: true, message: '请输入中文名称', trigger: 'blur'},
          ],
          enName: [
            {required: true, message: '请输入英文名称', trigger: 'blur'},
          ],
        }
      }
    },
    methods: {
      to() {
        this.$router.push({path: "/caseType/caseTypeList"});
      },
      changFileImage(file, imageFileList) {
        //选择文件后,给fileList对象赋值
        this.imageFileList = imageFileList
      },
      removeImageFile(file, fileList) {
        this.imageFileList = fileList
      },
      handleExceed(image, fileList) {
        this.$message.warning(`当前限制最多选择 4个文件`);
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.imageFileList = [];
      },
      submitForm(formName) {

        let _this = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = new FormData();
            for (let i = 0; i < this.imageFileList.length; i++) {
              // files[i] = this.fileList[i].raw;
              data.append("images",this.imageFileList[i].raw);
            }

            for (let key in this.formValue) {
              if (key != "exhibitionHall") {
                data.append(key, this.formValue[key])
              }
            }
            const _loading = loading(`文件上传中,请稍后...`)

            // this.show_progress = true
            const config = {
              onUploadProgress: progressEvent => {
                // progressEvent.loaded:已上传文件大小
                // progressEvent.total:被上传文件的总大小
                this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(0))
                _loading.setText('文件上传中,进度:' + this.progressPercent + "%") //更新dialog进度,优化体验
              },
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }


            this.addCaseType(data, _loading, config, _this)


          } else {
            this.$message({
              message: '请填写完整信息再后提交',
              type: 'error'
            });
            return false;
          }
        });
      },

      addCaseType(data, _loading, config, _this) {
        this.$http.post("casetype/addCaseType", data, config).then((res) => {

          _loading.close(); // 关闭加载框
          // this.show_progress = false
          this.progressPercent = 0
          if (res.data.success == true) {

            this.$message({
                message: "创建成功",
                type: 'success',
              }
            );
            setTimeout(function () {
              _this.imageFileList = [];// 提交完成清空附件列表
              _this.to();

            }, 100)

          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(function (error) { // 请求失败处理
        });
      },

    }
  }

js代码 

  import loading from "../../../loading";

  export default {
    name: "CaseTypeManager",
    data() {
      return {
        formValue: {
          id: 0,
          cnName: "",
          enName: "",
          image: ""
        },
        isUpdate: false,
        imageFileList: [],
        //上传文件进度条
        progressPercent: 0,
        show_progress: false,

        buttonTitle : "创建",

        rules:{
          cnName: [
            {required: true, message: '请输入中文名称', trigger: 'blur'},
          ],
          enName: [
            {required: true, message: '请输入英文名称', trigger: 'blur'},
          ],
        }
      }
    },
    methods: {
      to() {
        this.$router.push({path: "/caseType/caseTypeList"});
      },
      changFileImage(file, imageFileList) {
        //选择文件后,给fileList对象赋值
        this.imageFileList = imageFileList
      },
      removeImageFile(file, fileList) {
        this.imageFileList = fileList
      },
      handleExceed(image, fileList) {
        this.$message.warning(`当前限制最多选择 4个文件`);
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.imageFileList = [];
      },
      submitForm(formName) {

        let _this = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = new FormData();
            for (let i = 0; i < this.imageFileList.length; i++) {
              // files[i] = this.fileList[i].raw;
              data.append("images",this.imageFileList[i].raw);
            }

            for (let key in this.formValue) {
              if (key != "exhibitionHall") {
                data.append(key, this.formValue[key])
              }
            }
            const _loading = loading(`文件上传中,请稍后...`)

            // this.show_progress = true
            const config = {
              onUploadProgress: progressEvent => {
                // progressEvent.loaded:已上传文件大小
                // progressEvent.total:被上传文件的总大小
                this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(0))
                _loading.setText('文件上传中,进度:' + this.progressPercent + "%") //更新dialog进度,优化体验
              },
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }


            this.addCaseType(data, _loading, config)


          } else {
            this.$message({
              message: '请填写完整信息再后提交',
              type: 'error'
            });
            return false;
          }
        });
      },

      addCaseType(data, _loading, config) {
        let _this = this;
        this.$http.post("casetype/addCaseType", data, config).then((res) => {

          _loading.close(); // 关闭加载框
          // this.show_progress = false
          this.progressPercent = 0
          if (res.data.success == true) {

            this.$message({
                message: "创建成功",
                type: 'success',
              }
            );
            setTimeout(function () {
              _this.imageFileList = [];// 提交完成清空附件列表
              _this.to();

            }, 100)

          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(function (error) { // 请求失败处理
        });
      },

    }
  }

 核心  将文件添加到data中  

let data = new FormData();
            for (let i = 0; i < this.imageFileList.length; i++) {
              // files[i] = this.fileList[i].raw;
              data.append("images",this.imageFileList[i].raw);
            }

 将form添加到data

for (let key in this.formValue) {
              if (key != "exhibitionHall") {
                data.append(key, this.formValue[key])
              }
            }

使用axios提交到服务器

this.$http.post("casetype/addCaseType", data, config).then((res) => {}

 页面就是下面这个狗样子

 

后端代码

 @PostMapping("addCaseType")
    public Message addCaseType(CaseType caseType, @RequestParam MultipartFile[] images) {
        File tempFile = new File(serviceResPath + "casetype/"+caseType.getEnName()+"/");

        try {

            caseTypeService.save(caseType);
            FileUtil.createDir(tempFile);
            System.out.println(tempFile.isDirectory());
            for (int i=0;i<images.length;i++) {
                images[i].transferTo(new File(tempFile+("/"+(i+1)+".jpg")));
            }
        }catch (Exception e){
            e.printStackTrace();
            FileUtil.deleteDir(tempFile);
        }

        return Message.ok();
    }

 

 然后就完成了  想要代码我过两天在上传 工程项目

 

原文地址:https://blog.csdn.net/qq_36710445/article/details/112790359

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


el-menu 有个属性 :default-active="curActive"  el-menu-item有个属性:index=“home”这2个属性值对上号就自动定位了data(){ return{ curActive:"home" }; },
基础用法1<el-inputv-model="input1"palcehoder="请输入"></el-input>23varMain={4data(){5return{6input1:''7}8}9}10varCtor=Vue.extend(Main)11newCtor().$mount('#app&#03
 1.安装element-uinpminstallelement-ui-S 2.在main.js中importElementUIfrom'element-ui'import'element-ui/libheme-chalk/index.css'Vue.use(ElementUI)注意index.css的路径不要出错:在node_modules文件夹里node_modules\element-ui\lib\theme-c
layout布局通过基础的24分栏,可进行快速布局基础布局使用单一分栏创建基础的栅格布局,通过span属性指定每栏的大小<el-col:span="8"></el-col>1<el-row>2<el-col:span="8"><divclass="grid-contentbg-purple"></div>&
 今天做一个选择年份的功能,直接调用了ElementUI里面的DatePicker组件,官网上有该组件的用法介绍,讲得很清楚。 我的代码: 官网说明: 奇怪的事情发生了,我明明按照例子写了  value-format="yyyy" 可是获得的值却一直还是Date对象 仔细检查后,我突然发现我的v-model
  that.end 即为结束日期
vueelementUitree懒加载使用详情2018年11月21日11:17:04开心大表哥阅读数:3513 https://blog.csdn.net/a419419/article/details/84315751 背景:vue下使用elementUI文档:http://element-cn.eleme.io/#/zh-CN/componentree#tree-shu-xing-kong-jian需求:只保存二
环境搭建说明:1、全局安装angluar脚手架npminstall-g@angular/cli2、初始化项目(支持scss)ngnew项目名称--style=scss//进入项目cd项目名称运行代码可以是:serve或者npminstall(安装依赖)npmstart(运行)3、安装elementnpm
1、在写埋点监控项目的时候,需求是表格里面的数据后台传递过来为0,但是要求显示的时候为—,在elementUI判断,将prop去掉在下面加上<templateslot-scope="scope"><emplate>里面在写vue的判断,因为通过Scopedslot可以获取到row,column,$index和store(table内容的状态管理)的数据。2、
<el-table-columnprop="pubArea"//表格data中对应的字段column-key="pubArea"//过滤条件变化时根据此key判断是哪个表头的过滤label="报修类型"align="center"width=
1.npminstallbabel-plugin-component-D   然后.babelrc替换plugins 文件就在根目录下  2.组件中英文及自定义中英文importVueI18nfrom'vue-i18n'importenLocalefrom'element-ui/lib/locale/lang/en'importzhLocalefrom'element-ui/lib/locale/lang/zh-C
 <el-treeref="tree":data="menu.treeData":props="menu.defaultProps":filter-node-method="filterNode":expand-on-click-node=&quot
2019独角兽企业重金招聘Python工程师标准>>>使用vue+elementui的tree组件,elementui官网elementui的tree组件问题描述:tree层级过多时左右不可滚动问题解决:修改overflow属性值.el-tree-node>.el-tree-node_children{overflow:visible;} 其他相关链接:css--ov
首先elementUI的导航栏中的选中项的高亮显示时的字体颜色可以在属性中设置,但是高亮时的背景颜色不能设置,所以要自己修改高亮的背景颜色.el-menu-item.is-active{background-color:#00b4aa!important;} 在使用elementUI构建vue项目的时候会遇到页面刷新的时候子路由会保
1.首先创建Vue项目(使用vue-cli进行创建)创建项目文章指导地址: https://blog.csdn.net/assiduous_me/article/details/892086492.ElementUI:一套为开发者、设计师和产品经理准备的基于Vue2.0的桌面端组件库 链接地址:http://element.eleme.io/#/zh-CN3.正式开
使用vue开发项目,用到elementUI,根据官网的写法,我们可以自定义主题来适应我们的项目要求,下面来介绍一下两种方法实现的具体步骤,(可以参考官方文档自定义主题官方文档),先说项目中没有使用scss编写,用主题工具的方法(使用的较多)第一种方法:使用命令行主题工具使用vue-cli安装完项目并引
每页显示的序号都是一样的:<el-table:data="tableData"highlight-current-row@current-change="handleCurrentChange"><el-table-columntype="index"width="50"></el-table-column><el-table>根据
  记录一下自己踩的坑,控制element内的table的某列显示隐藏不能用v-show,而是要用v-if具体网上百度了,看一下v-show和v-if的区别吧猜测:由于el-table-column会生成多行标签元素,根据v-show是不支持template语法的,推断v-show不能显示隐藏多个元素 
样式重置单vue文件中重置全局重置多写一个style不加scrop,可能会影响全局样式待补充table单价数量小计3252?在ElementUI中,我需要获取row内的数据并进行计算,需要用到v-slot<el-table-columnlabel="小计"><templatev-slot="scope">{{scop
工作需要做一个带滑块效果的导航栏,初步想法是用element的导航组件去做,后面摸坑结合各位大佬的博客初步实现效果,话不多说,直接上代码,记录一下爬坑之旅1<template>2<divclass="y-nav">3<el-rowclass="nav">4<el-menu5:default-active="$route.