圖片或文件的二進(jìn)制存儲(chǔ)與數(shù)據(jù)庫(kù)映射設(shè)計(jì)
圖片或文件的二進(jìn)制存儲(chǔ)與數(shù)據(jù)庫(kù)映射設(shè)計(jì)
圖片或文件的二進(jìn)制存儲(chǔ)與數(shù)據(jù)庫(kù)映射設(shè)計(jì)
在某些系統(tǒng)中,文件或圖片可能需要存儲(chǔ)在數(shù)據(jù)庫(kù)中,而非本地磁盤(pán)。本文介紹如何將文件以二進(jìn)制形式存入數(shù)據(jù)庫(kù)并實(shí)現(xiàn)上傳與下載功能。
一、數(shù)據(jù)庫(kù)表結(jié)構(gòu)設(shè)計(jì)
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
);
二、實(shí)體類(lèi)映射
@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();
}
五、注意事項(xiàng)
- 圖片文件較大時(shí)建議壓縮或限制上傳大小
- 可將數(shù)據(jù)遷移至云存儲(chǔ),僅在數(shù)據(jù)庫(kù)保留元數(shù)據(jù)
這種方式適用于小文件、需要強(qiáng)事務(wù)一致性的場(chǎng)景。

浙公網(wǎng)安備 33010602011771號(hào)