Spring Boot——檔案上傳與下載
阿新 • • 發佈:2018-11-02
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wyl</groupId> <artifactId>SpringBootFile</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootFile</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thymeleaf模板外掛 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- devtools外掛,熱部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> </dependencies> </project>
2、application.properties檔案中取消模板檔案快取
spring.thymeleaf.cache=false
3、編寫模板檔案
file.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1 th:inlines="text">檔案上傳</h1> <form action="fileUpload" method="post" enctype="multipart/form-data"> <p>選擇檔案: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form> </body> </html> multifile.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1 th:inlines="text">檔案上傳</h1> <form action="multifileUpload" method="post" enctype="multipart/form-data" > <p>選擇檔案1: <input type="file" name="fileName"/></p> <p>選擇檔案2: <input type="file" name="fileName"/></p> <p>選擇檔案3: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form> </body> </html>
4、編寫Controller
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; @Controller public class FileUploadController { /* * 獲取file.html頁面 */ @RequestMapping("file") public String file(){ return "/file"; } /** * 實現檔案上傳 * */ @RequestMapping("fileUpload") @ResponseBody public String fileUpload(@RequestParam("fileName") MultipartFile file){ if(file.isEmpty()){ return "false"; } String fileName = file.getOriginalFilename(); int size = (int) file.getSize(); System.out.println(fileName + "-->" + size); String path = "F:/test" ; File dest = new File(path + "/" + fileName); if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在 dest.getParentFile().mkdir(); } try { file.transferTo(dest); //儲存檔案 return "true"; } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); return "false"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return "false"; } } /* * 獲取multifile.html頁面 */ @RequestMapping("multifile") public String multifile(){ return "/multifile"; } /** * 實現多檔案上傳 * */ @RequestMapping(value="multifileUpload",method=RequestMethod.POST)
/**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
public @ResponseBody String multifileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
if(files.isEmpty()){
return "false";
}
String path = "F:/test" ;
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
}
return "true";
}
}
5、測試
6、多檔案上傳中遇到的問題
org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field fileName exceeds its maximum permitted size of 1048576 bytes.
Spring Boot預設檔案上傳大小為2M,多文件上傳中總是出現檔案大小超出限度
解決方法:
a、在application.properties檔案中設定檔案大小
# Single file max size multipart.maxFileSize=50Mb # All files max size multipart.maxRequestSize=50Mb
但是,事實證明此種方法不能夠解決以上問題
b、在啟動類App.class檔案中配置Bean來設定檔案大小
import javax.servlet.MultipartConfigElement; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Hello world! * */ @SpringBootApplication @Configuration public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); SpringApplication.run(App.class, args); } /** * 檔案上傳配置 * @return */ @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //單個檔案最大 factory.setMaxFileSize("10240KB"); //KB,MB /// 設定總上傳資料總大小 factory.setMaxRequestSize("102400KB"); return factory.createMultipartConfig(); }
7、檔案下載
@RequestMapping("download")
public String downLoad(HttpServletResponse response){
String filename="2.jpg";
String filePath = "F:/test" ;
File file = new File(filePath + "/" + filename); if(file.exists()){ //判斷檔案父目錄是否存在 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + filename); byte[] buffer = new byte[1024]; FileInputStream fis = null; //檔案輸入流 BufferedInputStream bis = null; OutputStream os = null; //輸出流 try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while(i != -1){ os.write(buffer); i = bis.read(buffer); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("----------file download" + filename); try { bis.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }