多文件上传(图片)

spring+vue+mybaits实现多文件上传:

前端页面:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img{
            width: 100px;
        }
    </style>

</head>

<body>
    <div id="app">
        <h2>文件上传</h2>
        <input type="file" multiple @change="selectFile($event)">
        <input type="button" value="上传" @click="upFile($event)">
        <p>
            <img :src="'img/'+item" v-for="item in imgsArray" v-show="isUpload" >
        </p>
    </div>
    <script src="./js/axios.min.js"></script>
    <script src="./js/vue.min.js"> </script>
    <script>

        var app = new Vue({
            el: "#app",
            data: {
                file: null,
                filename: '',
                isUpload: false,
                imgs: ''
            },
            computed: {
                imgsArray:function() {
                    return this.imgs.split(',');
                }
            },
            methods: {
                selectFile(event) {
                    this.file = event.target.files;
                    console.log(this.file);
                },
                upFile(event) {

                    event.preventDefault(); //阻止默认事件
                    //创建一个表单数据对象
                    var formdata = new FormData();
                    //向表单数据对象中添加表单数据,指定名称与数据内容
                    // formdata.append("file",app.file);

                    for (let i = 0; i < this.file.length; i++) {
                        formdata.append("file", this.file[i])
                    }
                    axios.post("http://localhost:8080/upfile", formdata, {
                        Headers: {
                            "Content-Type": "multipart/form-data"
                        }
                    }).then(response => {
                        console.log(response.data);
                        var img= response.data;
                        app.imgs=img.substring(0,img.lastIndexOf(','));
                        //上传成功了
                        app.isUpload=true;
                        //指定上传成功后的文件名
                        // app.filename=response.data;

                    }).catch(error => {
                        console.log(error);
                    });
                    return false;
                }
            },
        })
    </script>
</body>

</html>

 

后台代码(控制层):

package com.example.mybatis2.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
//实现跨域
@CrossOrigin(origins = "*",maxAge = 3600)
public class UpFile {
    @Value("${prop.up-folder}")
    String upFolder;

    @PostMapping("/upfile")
    public String upFile(@RequestPart MultipartFile[] file) throws IOException {

        System.out.println(file);
        String name = "";
        //获取旧文件名称
        for (int i=0;i<file.length;i++) {
            String oldname = file[i].getOriginalFilename();
            //生成新文件名称
            String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."));
            //文件保存路径
            String path = upFolder + newname;
            name+=newname+",";
            //保存文件
            file[i].transferTo(new File(path));
        }

        return name;
    }
}

 

创建application.yaml文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/gomall?serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8
    username: root #用户名
    password: "000821" #密码
  #文件的限制大小
  servlet:
    multipart:
      max-file-size: 10MB  #文件最大值
      max-request-size: 10MB #请求最大值

mybatis:
  type-aliases-package: com.example.mybatis2.entity
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

# pagehelper
pagehelper:
  helperDialect: mysql  #数据库类型
  reasonable: true #查询合理化 当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页
  supportMethodsArguments: true  #支持方法参数 支持通过 Mapper 接口参数来传递分页参数
  params: count=countSql  #参数


#图片保存路径
prop:
  up-folder: D:\html\异步请求\img\

 

posted @ 2022-05-23 11:22  凡若沉曦'  阅读(44)  评论(0)    收藏  举报
js脚本