1. 程式人生 > 程式設計 >springboot+thymeleaf 檔案上傳功能的實現程式碼

springboot+thymeleaf 檔案上傳功能的實現程式碼

pom.xml

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

application.yml

spring:
 servlet:
  multipart:
   #上傳檔案總的最大值
   max-request-size: 10MB
   #上傳檔案的最大值
   max-file-size: 10MB

index.html 檔案上傳頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>檔案上傳</title>
</head>
<body>
  <p>單檔案上傳</p>
  <form method="post" action="/upload" enctype="multipart/form-data">
    <p><input type="file" name="file00"></p>
    <p><span th:text="${msg}"></span></p>
    <input type="submit" value="提交">
  </form>
 
  <hr/>
  <p>多檔案上傳</p>
  <form method="post" enctype="multipart/form-data" action="/batch">
    <p>檔案1:<input type="file" name="file"/></p>
    <p>檔案2:<input type="file" name="file"/></p>
    <p><input type="submit" value="上傳"/></p>
  </form>
 
</body>
</html>

hello.html 上傳成功的頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
 
  <p>單檔案上傳</p>
  <p th:text="${msg}"></p>
  <hr>
  <p>多檔案上傳</p>
  <ul>
    <li th:each="msg1:${msgList}" th:text="${msg1}"></li>
  </ul>
 
</body>
</html>

controller: 檔案上傳

import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
 
 
@Controller
public class FileUploadController {
 
  //單一檔案上傳
  @RequestMapping("/upload")
  public String uploadFile(@RequestParam("file00") MultipartFile file,Model model){
    String msg="";
    try {
      if(file.isEmpty()){
        model.addAttribute("msg","上傳失敗,請選擇檔案!");
        return "index";
      }
      String filename = file.getOriginalFilename();
      //String filePath = request.getServletContext().getRealPath("/upload");
      String filePath = ResourceUtils.getURL("classpath:").getPath()+"static/";
 
      //避免檔案重複覆蓋
      String uuid= UUID.randomUUID().toString().replaceAll("-","");
      //時間戳分類檔案
      String time = new SimpleDateFormat("YYYY-MM").format(new Date());
 
      String realPath = filePath+time+"/"+uuid+filename;
      File dest = new File(realPath);
      //檢測是否存在目錄,無,則建立
      if(!dest.getParentFile().exists()){
        dest.getParentFile().mkdirs();//新建資料夾 多級目錄
      }
 
      file.transferTo(dest);//檔案寫入
 
    } catch (IOException e) {
      e.printStackTrace();
    }
    model.addAttribute("msg","檔案上傳成功!");
    return "hello";
 
  }
 
  //多檔案上傳
  @RequestMapping("/batch")
  public String uploadMoreFiles(HttpServletRequest request,Model model){
    MultipartRequest request1 = (MultipartRequest)request;
    //猜測 file為 input 型別為 file
    List<MultipartFile> fileList = request1.getFiles("file");
    List<String> msgList = new ArrayList<>();
    System.out.println(fileList.size());
    try {
      String filepath = ResourceUtils.getURL("classpath:").getPath()+"static/";
      for (int i=1;i<=fileList.size();i++){
        MultipartFile file = fileList.get(i-1);
        if (file.isEmpty()){
          msgList.add("上傳第"+i+"個檔案失敗");
          model.addAttribute("msgList",msgList);
          continue;
        }
        String filename = file.getOriginalFilename();
        //避免檔案重複覆蓋
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        //時間戳分類檔案
        String time = new SimpleDateFormat("YYYY-MM").format(new Date());
 
        String realPath = filepath+time+"s/"+uuid+filename;
        File dest = new File(realPath);
        //System.out.println("realPath"+realPath);
        //檢測是否存在目錄,無,則建立
        if(!dest.getParentFile().exists()){
          dest.getParentFile().mkdirs();//新建資料夾 多級目錄
        }
        msgList.add("第"+i+"個檔案,上傳成功!");
        file.transferTo(dest);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    model.addAttribute("msgList",msgList);
    return "hello";
  }
 
}

測試:

檔案上傳檔案上傳2檔案上傳3

注:目前僅實現了檔案的上傳

計劃補充:檔案下載+上傳的圖片展示;

上傳的圖片展示:

遇到的問題: 直接使用realPath 作為圖片拼接地址 瀏覽器報 安全錯誤

notallow

使用字串拼接,也會報錯404

index = realPath.lastIndexOf("static");
upFilePaths.add("../"+realPath.substring(index));

到此這篇關於springboot+thymeleaf 檔案上傳功能的實現程式碼的文章就介紹到這了,更多相關springboot thymeleaf 檔案上傳內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!