SpringBoot项目中使用MultipartFile来上传文件
时间: 2023-10-13 21:16:31 浏览: 63
在SpringBoot项目中使用MultipartFile来上传文件,可以按照以下步骤:
1. 在前端页面中添加文件上传表单,例如:
```html
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
```
2. 在后端Controller中添加文件上传处理方法,例如:
```java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的字节数组
byte[] bytes = file.getBytes();
// TODO: 保存文件到指定位置
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败:" + e.getMessage();
}
}
```
在上面的代码中,我们首先检查上传的文件是否为空,然后获取文件名和文件的字节数组,并将其保存到指定位置。请注意,由于我们使用了`enctype="multipart/form-data"`,因此必须使用`@RequestParam`注解来获取文件参数。
3. 在SpringBoot的`application.properties`文件中配置文件上传的最大限制大小,例如:
```properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
```
在上面的配置中,我们将文件上传的最大限制大小设置为10MB。如果上传的文件大小超过了这个限制,将会抛出`MaxUploadSizeExceededException`异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)