Spring Boot實(shí)現(xiàn)文件上傳示例代碼
使用SpringBoot進(jìn)行文件上傳的方法和SpringMVC差不多,本文單獨(dú)新建一個(gè)最簡單的DEMO來說明一下。
主要步驟包括:
1、創(chuàng)建一個(gè)springboot項(xiàng)目工程,本例名稱(demo-uploadfile)。
2、配置 pom.xml 依賴。
3、創(chuàng)建和編寫文件上傳的 Controller(包含單文件上傳和多文件上傳)。
4、創(chuàng)建和編寫文件上傳的 HTML 測(cè)試頁面。
5、文件上傳相關(guān)限制的配置(可選)。
6、運(yùn)行測(cè)試。
項(xiàng)目工程截圖如下:
文件代碼:
<dependencies> <!-- spring boot web支持 --> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
package com.example.controller; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; /** * 文件上傳的Controller * * @author 單紅宇(CSDN CATOOP) * @create 2017年3月11日 */ @Controller public class FileUploadController { // 訪問路徑為:http://ip:port/upload @RequestMapping(value = "/upload", method = RequestMethod.GET) public String upload() { return "/fileupload"; } // 訪問路徑為:http://ip:port/upload/batch @RequestMapping(value = "/upload/batch", method = RequestMethod.GET) public String batchUpload() { return "/mutifileupload"; } /** * 文件上傳具體實(shí)現(xiàn)方法(單文件上傳) * * @param file * @return * * @author 單紅宇(CSDN CATOOP) * @create 2017年3月11日 */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { // 這里只是簡單例子,文件直接輸出到項(xiàng)目路徑下。 // 實(shí)際項(xiàng)目中,文件需要輸出到指定位置,需要在增加代碼處理。 // 還有關(guān)于文件格式限制、文件大小限制,詳見:中配置。 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 "上傳失敗,因?yàn)槲募强盏?"; } } /** * 多文件上傳 主要是使用了MultipartHttpServletRequest和MultipartFile * * @param request * @return * * @author 單紅宇(CSDN CATOOP) * @create 2017年3月11日 */ @RequestMapping(value = "/upload/batch", method = RequestMethod.POST) public @ResponseBody String batchUpload(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"; } }
package com.example.configuration; import javax.servlet.MultipartConfigElement; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; /** * 文件上傳配置 * * @author 單紅宇(CSDN CATOOP) * @create 2017年3月11日 */ public class FileUploadConfiguration { @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); // 設(shè)置文件大小限制 ,超出設(shè)置頁面會(huì)拋出異常信息, // 這樣在文件上傳的地方就需要進(jìn)行異常信息的處理了; factory.setMaxFileSize("256KB"); // KB,MB /// 設(shè)置總上傳數(shù)據(jù)總大小 factory.setMaxRequestSize("512KB"); // Sets the directory location where files will be stored. // factory.setLocation("路徑地址"); return factory.createMultipartConfig(); } }
@SpringBootApplication public class DemoUploadfileApplication { public static void main(String[] args) { SpringApplication.run(DemoUploadfileApplication.class, args); } }
<!DOCTYPE html> <html> <head> <title>文件上傳示例</title> </head> <body> <h2>文件上傳示例</h2> <hr/> <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>
<!DOCTYPE html> <html> <head> <title>批量文件上傳示例</title> </head> <body> <h2>批量文件上傳示例</h2> <hr/> <form method="POST" enctype="multipart/form-data" action="/upload/batch"> <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>
最后啟動(dòng)服務(wù),訪問 http://localhost:8080/upload 和 http://localhost:8080/upload/batch 測(cè)試文件上傳。
Demo源代碼下載地址:uploadfile_jb51.rar
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java?從json提取數(shù)組并轉(zhuǎn)換為list的操作方法
這篇文章主要介紹了Java?從json提取出數(shù)組并轉(zhuǎn)換為list,使用getJSONArray()獲取到j(luò)sonarray后,再將jsonArray轉(zhuǎn)換為字符串,最后將字符串解析為List列表,本文通過實(shí)例代碼給大家詳細(xì)講解,需要的朋友可以參考下2022-10-10java多態(tài)實(shí)現(xiàn)電子寵物系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java多態(tài)實(shí)現(xiàn)電子寵物系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02SpringBoot?Profile多環(huán)境配置方式
這篇文章主要介紹了SpringBoot?Profile多環(huán)境配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06SpringMVC @GetMapping注解路徑?jīng)_突問題解決
MD5對(duì)密碼進(jìn)行加密存儲(chǔ)是常見的一種加密方式,本文主要介紹了Java雙重MD5加密實(shí)現(xiàn)安全登錄,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Maven中dependency和plugins的繼承與約束
這篇文章主要介紹了Maven中dependency和plugins的繼承與約束,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12Java爬蟲范例之使用Htmlunit爬取學(xué)校教務(wù)網(wǎng)課程表信息
htmlunit 是一款開源的java 頁面分析工具,讀取頁面后,可以有效的使用htmlunit分析頁面上的內(nèi)容。項(xiàng)目可以模擬瀏覽器運(yùn)行,被譽(yù)為java瀏覽器的開源實(shí)現(xiàn)。今天我們用這款分析工具來爬取學(xué)校教務(wù)網(wǎng)課程表信息2021-11-11