一、问题描述
目前我们在开发的时候,图片大部分都存在文件服务器(例如minio),数据库中只存储对应的访问地址,前端在访问的时候只需用文件服务器的地址拼接上对应的图片地址即可,但在有些情况下需要把图片以base64的形式存储在数据库中。此时如果直接返回base64数据给前端的话,会造成返回数据量过大,被浏览器给组织掉,从而无法正常加载数据。
二、问题解决
1、提供相关接口可以查询对应的base64数据并转成在线图片,即通过ip:port拼上URL即可访问图片
/**
* 根据id和列名返回对应的图片
* @param response
* @param id
* @param column
* @return
*/
public void getImageByColumn(HttpServletResponse response, Integer id, String column) {
String carDatas = this.carDataMapper.getCarDataByColumn(id, column);
base64ToImage(response, carDatas);
}
/**
* 根据id和列名查询对应字段值
* @param id
* @param column
* @return
*/
@Select("SELECT " +
"${column} " +
"FROM car_data WHERE id = #{id}")
String getCarDataByColumn(Integer id, String column);
/**
* base64图片转图片返回给前端
* @param response
* @param base64
*/
public static void base64ToImage(HttpServletResponse response, String base64) {
try {
//设置输出文件格式
response.setContentType("image/png");
//将Base64格式的图片解码成字节
byte[] bytes = Base64.getDecoder().decode(base64);
InputStream inStream = new ByteArrayInputStream(bytes);
OutputStream outputStream = null;
outputStream = new BufferedOutputStream(response.getOutputStream());
//创建存放文件内容的数组
byte[] buff = new byte[1024];
//所读取的内容使用n来接收
int n;
//当没有读取完时,继续读取,循环
while ((n = inStream.read(buff)) != -1) {
//将字节数组的数据全部写入到输出流中
outputStream.write(buff, 0, n);
}
//强制将缓存区的数据进行输出
outputStream.flush();
//关流
outputStream.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2、在分页查询接口中返回对应数据的url
public PageInfo<FaceData> getFaceDatas(int page, int count, String communityId, Integer passType, String personName, String idNumber, Integer type, Long start, Long end) {
PageHelper.startPage(page, count);
List<FaceData> faceDatas = this.faceDataMapper.getFaceDatas(communityId, passType, personName, idNumber, type, start, end);
faceDatas.stream().forEach(faceData -> {
faceData.setPhotoBase1(faceData.getPhotoBase1() == null ? null : "/faceData/getImageByColumn?id=" + faceData.getId() + "&column=photoBase1");
faceData.setPhotoBase2(faceData.getPhotoBase2() == null ? null : "/faceData/getImageByColumn?id=" + faceData.getId() + "&column=photoBase2");
faceData.setPhotoBase3(faceData.getPhotoBase3() == null ? null : "/faceData/getImageByColumn?id=" + faceData.getId() + "&column=photoBase3");
faceData.setBigImageBase64(faceData.getBigImageBase64() == null ? null : "/faceData/getImageByColumn?id=" + faceData.getId() + "&column=bigImageBase64");
});
return new PageInfo<>(faceDatas);
}