Spring boot實現(xiàn)文件上傳實例(多文件上傳)
文件上傳主要分以下幾個步驟:
(1)新建maven java project;
(2)在pom.xml加入相應依賴;
(3)新建一個表單頁面(這里使用thymleaf);
(4)編寫controller;
(5)測試;
(6)對上傳的文件做一些限制;
(7)多文件上傳實現(xiàn)
(1)新建maven Java project
新建一個名稱為spring-boot-fileupload maven Java項目;
(2)在pom.xml加入相應依賴;
加入相應的maven依賴,具體看以下解釋:
<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.example</groupId> <artifactId>spring-boot-fileupload</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- spring boot 父節(jié)點依賴, 引入這個之后相關的引入就不需要添加version配置, spring boot會自動選擇最合適的版本進行添加。 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <dependencies> <!-- spring boot web支持:mvc,aop... --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thmleaf模板依賴. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <!-- 編譯版本; --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
(3)新建一個表單頁面(這里使用thymleaf)
在src/main/resouces新建templates,在templates下新建一個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> <title>Hello World!</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="/upload"> <p> 文件:<input type="file" name="file" /> </p> <p> <input type="submit" value="上傳" /> </p> </form> </body> </html>
(4)編寫controller;
編寫controller進行測試,這里主要實現(xiàn)兩個方法:其一就是提供訪問的/file路徑;其二就是提供post上傳的/upload方法,具體看代碼實現(xiàn):
@Controller public class FileUploadController { // 訪問路徑為:http://127.0.0.1:8080/file @RequestMapping("/file") public String file() { return "/file"; } /** * 文件上傳具體實現(xiàn)方法; * * @param file * @return */ @RequestMapping("/upload") @ResponseBody public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { /* * 這段代碼執(zhí)行完畢之后,圖片上傳到了工程的跟路徑; 大家自己擴散下思維,如果我們想把圖片上傳到 * d:/files大家是否能實現(xiàn)呢? 等等; * 這里只是簡單一個例子,請自行參考,融入到實際中可能需要大家自己做一些思考,比如: 1、文件路徑; 2、文件名; * 3、文件格式; 4、文件大小的限制; */ BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File( file.getOriginalFilename()))); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } catch (IOException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } return "上傳成功"; } else { return "上傳失敗,因為文件是空的."; } } // 訪問路徑為:http://127.0.0.1:8080/file @RequestMapping("/mutifile") public String mutifile() { return "/mutifile"; }
(5)編寫Application.java然后測試
Application沒什么代碼,就是Spring Boot的啟動配置,具體如下:
package com.example.controller; import javax.servlet.MultipartConfigElement; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
然后你就可以訪問:http://127.0.0.1:8080/file 進行測試了,文件上傳的路徑是在工程的跟路徑下,請刷新查看,其它的請查看代碼中的注釋進行自行思考
(6)對上傳的文件做一些限制;
對文件做一些限制是有必要的,在Application.java進行編碼配置:。
@Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //// 設置文件大小限制 ,超了,頁面會拋出異常信息,這時候就需要進行異常信息的處理了; factory.setMaxFileSize("128KB"); //KB,MB /// 設置總上傳數(shù)據(jù)總大小 factory.setMaxRequestSize("256KB"); //Sets the directory location where files will be stored. //factory.setLocation("路徑地址"); return factory.createMultipartConfig(); }
(7)多文件上傳實現(xiàn)
多文件對于前段頁面比較簡單,具體代碼實現(xiàn):
在src/resouces/templates/mutifile.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> <title>Hello World!</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="/batch/upload"> <p>文件1:<input type="file" name="file" /></p> <p>文件2:<input type="file" name="file" /></p> <p>文件3:<input type="file" name="file" /></p> <p><input type="submit" value="上傳" /></p> </form> </body> </html>
FileUploadController中新增兩個方法:
// 訪問路徑為:http://127.0.0.1:8080/mutifile @RequestMapping("/mutifile") public String mutifile() { return "/mutifile"; } /** * 多文件具體上傳時間,主要是使用了MultipartHttpServletRequest和MultipartFile * * @param request * @return */ @RequestMapping(value = "/batch/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request) { List<MultipartFile> files = ((MultipartHttpServletRequest) request) .getFiles("file"); MultipartFile file = null; BufferedOutputStream stream = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); stream = new BufferedOutputStream(new FileOutputStream( new File(file.getOriginalFilename()))); stream.write(bytes); stream.close(); } catch (Exception e) { stream = null; return "You failed to upload " + i + " => " + e.getMessage(); } } else { return "You failed to upload " + i + " because the file was empty."; } } return "upload successful"; }
訪問路徑:http://127.0.0.1:8080/mutifile 進行測試。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Spring注解驅(qū)動之關于@Bean注解指定初始化和銷毀的方法
這篇文章主要介紹了Spring注解驅(qū)動之關于@Bean注解指定初始化和銷毀的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09IntelliJ IDEA : .java文件左下角顯示"J"圖標的問題
IntelliJ IDEA : .java文件 左下角顯示“J”,并且不能執(zhí)行代碼,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-10-10springboot接口接收數(shù)組及多個參數(shù)的問題及解決
這篇文章主要介紹了springboot接口接收數(shù)組及多個參數(shù)的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11IntelliJ IDEA 老司機居然還沒用過 Stream Trace功能(問題小結(jié))
很多朋友酷愛Java8 Stream功能,但是在使用過程中總不是那么順利,下面通過本文給大家分享idea Stream Trace調(diào)試過程遇到的問題,需要的朋友參考下吧2021-05-05