springboot上传图片
时间: 2023-07-02 21:22:47 浏览: 37
在 Spring Boot 中上传图片可以通过以下步骤实现:
1. 添加依赖:在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
```
2. 创建 Controller:创建一个处理上传图片的 Controller,如下所示:
```java
@RestController
public class ImageController {
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
// 获取上传文件的文件名
String fileName = file.getOriginalFilename();
// 设置文件存储路径
String filePath = "D:/upload/";
File dest = new File(filePath + fileName);
// 检查文件存储路径是否存在,不存在则创建路径
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 保存文件到指定路径
file.transferTo(dest);
return "上传成功";
}
}
```
3. 创建 HTML 页面:创建一个上传图片的 HTML 页面,如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
```
4. 运行应用程序:运行应用程序,在浏览器中访问上传图片的 HTML 页面,选择要上传的图片,点击上传按钮即可上传图片到指定路径。
以上就是在 Spring Boot 中上传图片的步骤。