一起學習Springboot(六):檔案上傳
阿新 • • 發佈:2018-12-19
本篇文章主要介紹在Springboot中如何上傳檔案
引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
上傳頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data" method="post" action="/upload"> <table> <tr><td><input type="file" name="file" /></td></tr> <tr><td><input type="submit" value="上傳" /></td></tr> </table> </form> </body> </html>
application.properties配置檔案
#限制請求上傳單個檔案大小
spring.servlet.multipart.max-file-size=5KB
#限制請求上傳總檔案大小
spring.servlet.multipart.max-request-size=5KB
#spring.http.multipart.max-file-size=5KB 老版本
#spring.http.multipart.max-request-size= 5KB 老版本
Controller類
package com.example.springboot_uploadfile.controller; import ch.qos.logback.core.util.FileUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; /** * @author XuJD * @create 2018-11-01 18:02 **/ @Controller public class IndexController { @RequestMapping("/index") public String index(){ return "index"; } @ResponseBody @RequestMapping("/upload") public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){ String fileName = file.getOriginalFilename(); try { //檔案上傳到目標地址 String filePath = "G:\\demo\\fileUpload\\"; File targetFile = new File(filePath); if(!targetFile.exists()){ targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath+fileName); out.write(file.getBytes()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return "上傳成功"; } }
測試 上傳一個超過5KB大小的檔案試試,可以發現會報如下錯誤