阳光沙滩博客系统-门户图片访问

我们返回给前端的图片,都是以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();
    }
}
1
2
3
4
5
6
7
8

实现,是不是跟我们的图灵验证码一样呀。

@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();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
上次更新: 2022/03/28, 23:04:38