跳到主要内容

Mybatis存取文件(Blob)

· 阅读需 2 分钟

先说一个常识性的:mysql中blob对应java中的byte[]类型

blob的四种类型

提示

如果你存储的文件过大,数据库的性能会下降很多。

类型最大存储
tinyblob最大255字节
blob65k
mediumblob16m
longblob4g

代码

建表blobtest

我这里测试的图108kb,所以用的mediumblob类型

CREATE TABLE `blob_test` (
`id` int NOT NULL AUTO_INCREMENT,
`img` mediumblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

对应实体对象BlobTest:

@Data
@TableName("blob_test")
public class BlobTest {
@TableId
private Integer id;
private byte[] img;
}

定义接口:

blobTestMapper用的mybatis-plus

@RestController
@RequestMapping("blobTest")
public class jdbcTestController {

@Resource
private BlobTestMapper blobTestMapper;
@Resource
private HttpServletResponse response;

@PostMapping("save")
public String save(@RequestPart("imgFile") MultipartFile imgFile) {
BlobTest blobTest = new BlobTest();
// 文件流 转 byte[]
try (InputStream is = imgFile.getInputStream();){
byte[] img = new byte[is.available()];
is.read(img);
blobTest.setImg(img);
}catch (IOException e) {
throw new RuntimeException(e);
}
blobTestMapper.insert(blobTest);
return "OK,id is " + blobTest.getId();
}
@GetMapping("get")
public void get(Integer id){
BlobTest blobTests = blobTestMapper.selectById(id);
byte[] img = blobTests.getImg();
try (ServletOutputStream outputStream = response.getOutputStream();){
outputStream.write(img);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

}

测试结果

  • 保存后,从数据库中查看结果:

图

  • 从浏览器访问该图片

图

数据库支持存文件,但请不要滥用,相比文件,数据资源更重要。