開發准備:
1.快速搭建一個springboot項目
2.准備上傳頁面 提供form表單 post提交 multipart/form-data
3.開發控制器 使用MultipartFile形式接收接收的變量名必須和上傳頁面的name一至 將接收到的文件放入到執行目錄中即可
pom.xml文件引入的依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--添加jsp支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--引入commons-fileUpload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> </dependencies>
jsp頁面代碼:
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>文件上傳頁面</title> 5 </head> 6 <body> 7 <center> 8 <form action="${pageContext.request.contextPath}/fc/upload" method="post" enctype="multipart/form-data"> 9 <input type="file" name="aaa"> 10 <input type="submit" value="上傳"> 11 </form> 12 </center> 13 </body> 14 </html>
Controller代碼
1 package com.liusha.ems.controller; 2 3 import org.apache.commons.io.FilenameUtils; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.multipart.MultipartFile; 7 8 import javax.servlet.http.HttpServletRequest; 9 import java.io.File; 10 import java.io.IOException; 11 import java.text.SimpleDateFormat; 12 import java.util.Date; 13 import java.util.UUID; 14 15 @Controller 16 @RequestMapping("/fc") 17 public class FileController { 18 19 @RequestMapping("/getFile") 20 public String getFile(){ 21 return "/upload"; 22 } 23 24 //處理文件上傳的方法 25 @RequestMapping("/upload") 26 public String upload(MultipartFile aaa, HttpServletRequest request) throws IOException { 27 28 //根據相對獲取絕對路徑(文件上傳到的保存位置) 29 String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/files"); 30 //獲取文件后綴 31 String extension = FilenameUtils.getExtension(aaa.getOriginalFilename()); 32 //文件名我這里使用UUID和時間組成的 33 String newFileNamePrefix= UUID.randomUUID().toString().replace("-","")+ 34 new SimpleDateFormat("yyyyMMddHHssSSS").format(new Date()); 35 String newFileName=newFileNamePrefix+"."+extension; 36 //處理文件上傳 37 aaa.transferTo(new File(realPath,newFileName)); 38 39 //上傳成功后跳轉到的路徑 40 return "redirect:/fc/getFile"; 41 } 42 43 }