SprinbBoot 文件上传
后端(Spring Boot)
- 添加依赖:确保你的
pom.xml
文件中包含了Spring Boot的Web依赖。
xml
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 其他依赖 -->
</dependencies>
- 配置文件:在
application.properties
或application.yml
中配置文件上传的相关参数,例如最大文件大小。- 如果不配置spring.servlet.multipart.max-file-size和spring.servlet.multipart.max-request-size,那么文件上传的默认限制将由Spring Boot使用的底层库(通常是Tomcat)来决定。
properties
# application.properties
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
- 创建文件MultipartFile类:
java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;@RestController
public class FileUploadController {@PostMapping("/upload")public String handleFileUpload(@RequestParam("file") MultipartFile file) {try {// 检查文件是否为空if (file.isEmpty()) {return "文件不能为空";}// 保存文件到本地目录String destPath = "uploads/" + file.getOriginalFilename();file.transferTo(new File(destPath));return "文件上传成功,路径:" + destPath;} catch (IOException e) {e.printStackTrace();return "文件上传失败";}}
}
- 异常处理(可选):你可以创建一个异常处理器来处理文件上传过程中可能出现的异常。
java
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {@Overrideprotected ResponseEntity<Object> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exc, HttpHeaders headers, HttpStatus status, WebRequest request) {String message = "不能上传超过 " + exc.getMaxSize() + " 的文件";return new ResponseEntity<>(message, HttpStatus.PAYLOAD_TOO_LARGE);}
}