springboot文件上传
时间: 2023-06-28 10:04:47 浏览: 143
在Spring Boot中,文件上传可以使用Spring MVC提供的MultipartResolver来实现。
首先,在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
```
然后,在Controller中定义一个方法来处理文件上传请求:
```
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
String uploadDir = "uploads/";
FileUploadUtil.saveFile(uploadDir, fileName, file);
return "File uploaded successfully!";
}
```
其中,@PostMapping("/upload")表示接收POST请求,并且请求路径为/upload。
@RequestParam("file")表示接收名为file的文件参数。
FileUploadUtil.saveFile(uploadDir, fileName, file)是一个自定义的工具类,用于将文件保存到指定的目录中:
```
public class FileUploadUtil {
public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save file: " + fileName, ioe);
}
}
}
```
最后,需要在application.properties中配置上传文件大小限制和临时文件存储路径:
```
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.location=/tmp
```
以上就是Spring Boot中实现文件上传的基本步骤。
阅读全文