我们有时候希望将一些小文件可以直接存入数据库,而不是通过OSS,所以记录一下。
1.建立数据库存储字段
mysql中对应二进制存储字段为blog,TinyBlob 最大 255B,Blob 最大 65K,MediumBlob 最大 16M,LongBlob 最大 4G,实际使用中根据需要存入的数据大小定义不同的BLOB类型。需要注意的是:如果你存储的文件过大,数据库的性能会下降很多。本次测试我们使用的字段类型为MediumBlob。
2.实现代码
首先是存储代码,将文件转换为二进制,存入数据库中,我们是使用的springboot项目:
@GetMapping("/save-annex")
public String saveAnnex() {
UserInfo userInfo = new UserInfo();
userInfo.setName("liu-yi-fei");
//设置文件名后缀
userInfo.setExtName("神仙姐姐");
File file = new File("C:\Users\Administrator\Desktop\神仙姐姐.txt");
//将文件转换为二进制进行存储
byte[] bytes = BinUtil.fileToBinArray(file);
userInfo.setAnnex(bytes);
userService.save(userInfo);
return "success";
}
然后就是下载代码:
@GetMapping("/download-annex")
public void downloadAnnex(HttpServletResponse response) throws IOException {
UserInfo userInfo = userService.getById(3);
//设置文件名的时候需要encode一下,否则中文文件名下载会有问题
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(userInfo.getName()) + "." + userInfo.getExtName());
response.setCharacterEncoding("utf-8");
byte[] annex = userInfo.getAnnex();
//二进制转换为流
StreamUtils.copy(annex, response.getOutputStream());
}
3.实现效果
上传:
下载: