使用SpringBoot進行文件上傳的方法和SpringMVC差不多,本文單獨新建一個最簡單的springboot工程來說明一下。
主要步驟包括:
1、創建一個springboot項目工程,本例名稱(springboot)。
2、配置 pom.xml 依賴。
3、創建和編寫文件上傳的 Controller(包含單文件上傳)。
4、創建和編寫文件上傳的 HTML 測試頁面。
5、文件上傳相關限制的配置(可選)。
6、運行測試。
項目工程截圖如下:
文件代碼:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
package com.example.springboot.controller; import com.example.springboot.util.FileUtil; 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; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.util.List; import java.util.stream.Stream; /** *文件上傳的Controller * @author lrd * @date 2018/10/22 * @param * @param null * @return null */ @Controller public class UploadFileController { @RequestMapping(value = "/upload",method = RequestMethod.GET) public String upload(){ return "/upload"; } /** *單文件上傳 * @param file * @return String */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file")MultipartFile file,HttpServletRequest request){ String contentType = file.getContentType(); //圖片文件類型 String fileName = FileUtil.getFileName(file.getOriginalFilename()); //圖片名字 String filePath = "C:\\Users\\Administrator\\IdeaProjects\\springboot\\src\\main\\resources\\static\\upload\\"; try { //調用文件處理類FileUtil,處理文件,將文件寫入指定位置 FileUtil.uploadFile(file.getBytes(),filePath,fileName); } catch (Exception e) { e.printStackTrace(); } return filePath; } }
package com.example.springboot.util; import java.io.File; import java.io.FileOutputStream; import java.util.UUID; /** *FileUtil工具類,實現uploadFile方法 * @author lrd * @date 2018/10/23 * @param * @param null */ public class FileUtil { /** *文件上傳工具類服務方法 * @param * @param file * @param filePath * @param fileName * @return */ public static void uploadFile(byte[] file,String filePath,String fileName)throws Exception{ File targetFile = new File(filePath); if(!targetFile.exists()){ targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath+fileName); out.write(file); out.flush(); out.close(); } /** *獲取文件後綴名 * @param * @param fileName * @return String */ public static String getSuffix(String fileName){ return fileName.substring(fileName.lastIndexOf(".")); } /** *生成新的文件名 * @param * @param fileOriginName 源文件名 * @return */ public static String getFileName(String fileOriginName){ return getUUID() + getSuffix(fileOriginName); } /** *生成文件名 * @param * @param * @return */ public static String getUUID(){ return UUID.randomUUID().toString().replace("-",""); } }
package com.example.springboot.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; /** *文件上傳配置 * @author lrd * @date 2018/10/22 * @param * @param null * @return null */ @Configuration public class UploadFileConfiguration { @Bean public MultipartConfigElement multipartConfigElement(){ MultipartConfigFactory factory = new MultipartConfigFactory(); // 設置文件大小限制 ,超出設置頁面會拋出異常信息 factory.setMaxFileSize("256KB"); //設置總上傳文件大小 factory.setMaxRequestSize("512KB"); return factory.createMultipartConfig(); } }
package com.example.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); System.out.println("啓動成功"); } } 注:因爲我在pom.xml中添加了數據庫組件,所以autoconfig會去讀取數據源配置,而我新建的項目還沒有配置數據源,所以會導致啓動報錯 Failed to auto-configure a DataSource,那麼在@SpringBootApplication中添加exclude ={DataSourceAutoConfiguration.class},排除此類的autoconfig,這樣就可以正常啓動運行了。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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>
最後啓動Application服務,訪問 http://localhost:8080/upload 測試文件上傳。