图片或文件的二进制存储与数据库映射设计
图片或文件的二进制存储与数据库映射设计
图片或文件的二进制存储与数据库映射设计
在某些系统中,文件或图片可能需要存储在数据库中,而非本地磁盘。本文介绍如何将文件以二进制形式存入数据库并实现上传与下载功能。
一、数据库表结构设计
CREATE TABLE file_storage (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
filename VARCHAR(255),
content_type VARCHAR(100),
data LONGBLOB,
upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
二、实体类映射
@Entity
@Table(name = "file_storage")
public class FileStorage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String filename;
private String contentType;
@Lob
@Column(columnDefinition = "LONGBLOB")
private byte[] data;
private Timestamp uploadTime;
}
三、文件上传接口
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
FileStorage fs = new FileStorage();
fs.setFilename(file.getOriginalFilename());
fs.setContentType(file.getContentType());
fs.setData(file.getBytes());
repository.save(fs);
return "上传成功";
}
四、文件下载接口
@GetMapping("/download/{id}")
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
FileStorage fs = repository.findById(id).orElseThrow();
response.setContentType(fs.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + fs.getFilename());
ServletOutputStream out = response.getOutputStream();
out.write(fs.getData());
out.flush();
}
五、注意事项
- 图片文件较大时建议压缩或限制上传大小
- 可将数据迁移至云存储,仅在数据库保留元数据
这种方式适用于小文件、需要强事务一致性的场景。