springBoot如何上传图片
时间: 2024-05-10 11:16:49 浏览: 67
在Spring Boot中上传图片可以使用Spring MVC和Apache Commons FileUpload组件来实现。下面是一个简单的示例代码:
1. 首先在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
```
2. 在Controller中添加以下代码:
```
@PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + fileName);
Files.write(path, bytes);
return ResponseEntity.ok("File uploaded successfully");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
}
}
```
3. 在HTML表单中添加文件上传组件:
```
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
```
在这个例子中,上传的文件将被保存在项目根目录下的“uploads”文件夹中。你可以根据具体的需求修改代码。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)