我们返回给前端的图片,都是以json的形式返回,只是一个url,当用户通过这个Url访问的时候,我们才把图片数据写到前端
API接口
@GetMapping("/{imageId}")
public void getImage(HttpServletResponse response, @PathVariable("imageId") String imageId) {
try {
imageService.viewImage(response, imageId);
} catch (IOException e) {
e.printStackTrace();
}
}
实现,是不是跟我们的图灵验证码一样呀。
@Override
public void viewImage(HttpServletResponse response, String imageId) throws IOException {
//配置的目录已知
//根据尺寸来动态返回图片给前端
//好处:减少带宽占用,传输速度快
//缺点:消耗后台的CPU资源
//推荐做法:上传上来的时候,把图片复制成三个尺寸:大,中,小
//根据尺寸范围,返回结果即可
//需要日期
String[] paths = imageId.split("_");
String dayValue = paths[0];
String format = simpleDateFormat.format(Long.parseLong(dayValue));
log.info("viewImage format == > " + format);
//ID
String name = paths[1];
//需要类型
String type = name.substring(name.length() - 3);
//使用日期的时间戳_ID.类型
String targetPath = imagePath + File.separator + format + File.separator +
type +
File.separator + name;
log.info("get image target path === > " + targetPath);
File file = new File(targetPath);
OutputStream writer = null;
FileInputStream fos = null;
try {
response.setContentType("image/png");
writer = response.getOutputStream();
//读取
fos = new FileInputStream(file);
byte[] buff = new byte[1024];
int len;
while ((len = fos.read(buff)) != -1) {
writer.write(buff, 0, len);
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
if (writer != null) {
writer.close();
}
}
}