1. 程式人生 > 其它 >多檔案上傳(圖片)

多檔案上傳(圖片)

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\