一。建表语句
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";
}