一。建表语句
DROP TABLE IF EXISTS `表名`;
CREATE TABLE `表名` (
`id` bigint NOT NULL AUTO_INCREMENT,
`photo` MediumBlob NOT NULL COMMENT '二进制流',
`create_time` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '创建时间',
`last_modify_time` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '更新时间',
PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 comment '表名描述';
二。保存到mysql
public void uploadFile2Mysql(MultipartFile file) {
try {
byte[] data;
data = file.getBytes();
实体.setPhoto(data);
保存到mysql中
}catch (Exception e){
e.printStackTrace();
}
}
三。回显 页面请求后台接口
<img src="/getImageByMysql?id='+数据库数据id+'">
四。后台接口回显
@RequestMapping(value ="/getImageByMysql")
public String getImageByMysql(HttpServletRequest request, HttpServletResponse response, Long id) {
// 取路径
OutputStream os = null;
ByteArrayInputStream fis = null;
try {
根据ID获取实体
fis = new ByteArrayInputStream(数据库中保存的二进制流);
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 8];
while ((count = fis.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "personalCenter";
}
博客主要围绕图片二进制流在MySQL中的处理展开。包含建表语句,介绍如何将图片以二进制流形式保存到MySQL,还阐述了页面请求后台接口实现图片回显,以及后台接口回显图片的相关内容。
1886

被折叠的 条评论
为什么被折叠?



