SpringBoot项目数据库存储本地图片路径
时间: 2025-03-01 10:09:02 浏览: 61
### 实现 Spring Boot 中将本地图片路径保存到数据库
为了实现这一功能,在 Spring Boot 项目中可以创建实体类用于映射数据库表,编写控制器来处理前端上传请求并保存文件至服务器磁盘上指定位置,最后把该文件的位置信息存入数据库。
#### 创建实体类 ImageEntity 映射数据库中的记录
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class ImageEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String filePath;
// Getters and Setters
}
```
此代码定义了一个简单的 JPA 实体 `ImageEntity` 来表示图像数据模型[^1]。
#### 编写 Repository 接口操作数据库
利用 Spring Data 提供的功能简化对持久层的操作:
```java
import org.springframework.data.jpa.repository.JpaRepository;
public interface ImageRepository extends JpaRepository<ImageEntity, Long> {}
```
这段声明式的接口允许应用程序轻松执行 CRUD 操作而无需手动编码 SQL 查询语句。
#### 控制器部分负责接收 HTTP 请求并将接收到的数据保存下来
```java
import org.springframework.beans.factory.annotation.Autowired;
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.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@RestController
public class ImageController {
@Autowired
private ImageRepository imageRepo;
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file){
try{
if(!file.isEmpty()){
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + UUID.randomUUID().toString());
Files.write(path, bytes);
ImageEntity imgRecord = new ImageEntity();
imgRecord.setFilePath(path.toString());
imageRepo.save(imgRecord);
return "You successfully uploaded!";
}
} catch (Exception e) {
return "Failed to upload.";
}
return "Please select a valid file.";
}
}
```
上述片段展示了如何构建 RESTful Web Service API 处理 POST 方法提交过来的多部件形式文件,并将其内容写出到特定目录下;同时更新关联的对象实例属性值为新生成文件所在绝对地址再调用 save 方法完成入库动作[^2]。
阅读全文
相关推荐


















