1. 程式人生 > 程式設計 >springboot實現多檔案上傳功能

springboot實現多檔案上傳功能

本文實現springboot的多檔案上傳,首先建立一個springboot專案,新增spring-boot-starter-web依賴。

然後在resources下的static資料夾下建立uploads.html檔案,檔案內容如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>多檔案上傳</title>
</head>
<body>
<form action="/uploads" method="post" enctype="multipart/form-data">
  <input type="file" name="uploadFiles" value="請選擇檔案" multiple>
  <input type="submit" value="上傳">
</form>
</body>
</html>

然後編寫Controller類

@RestController
public class FilesUploadController {
 
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
 
  @RequestMapping("/uploads")
  public String upload(MultipartFile[] uploadFiles,HttpServletRequest request) {
    List list = new ArrayList();//儲存生成的訪問路徑
    if (uploadFiles.length > 0) {
      for (int i = 0; i < uploadFiles.length; i++) {
        MultipartFile uploadFile = uploadFiles[i];
        //設定上傳檔案的位置在該專案目錄下的uploadFile資料夾下,並根據上傳的檔案日期,進行分類儲存
        String realPath = request.getSession().getServletContext().getRealPath("uploadFile");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
          folder.mkdirs();
        }
 
        String oldName = uploadFile.getOriginalFilename();
        System.out.println("oldName = " + oldName);
        String newName = UUID.randomUUID().toString() + oldName.
            substring(oldName.lastIndexOf("."),oldName.length());
        System.out.println("newName = " + newName);
        try {
          //儲存檔案
          uploadFile.transferTo(new File(folder,newName));
 
          //生成上傳檔案的訪問路徑
          String filePath = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + "/uploadFile" + format + newName;
          list.add(filePath);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      return list.toString();
    } else if (uploadFiles.length == 0) {
      return "請選擇檔案";
    }
    return "上傳失敗";
  }
}

相比於單檔案上傳,這裡就多了一個遍歷的過程。

檔案上傳常見配置:

#是否開啟檔案上傳支援,預設是true
spring.servlet.multipart.enabled=true 
#檔案寫入磁碟的閾值,預設是0
spring.servlet.multipart.file-size-threshold=0
#上傳檔案的臨時儲存位置
spring.servlet.multipart.location=D:\\upload
#單個檔案的最大值,預設是1MB
spring.servlet.multipart.max-file-size=1MB
#多個檔案上傳時的總大小 值,預設是10MB
spring.servlet.multipart.max-request-size=10MB
#是否延遲解析,預設是false
spring.servlet.multipart.resolve-lazily=false

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。