springboot implement a web browser to download the picture function (picture in binary form stored in the database)

1, the realization of ideas:

① binary data to the server front-end url picture id, find the corresponding picture based on the id

② entity class with the image byte [] data reception binary

Set your browser settings ③repsonse response

④response.getWriter () for processing character data stream

Byte stream data ⑤response.getOutputStream () for outputting character or binary data stream

Because it is byte, here without ④ ⑤

    /**
     * 功能描述:
     * @param: id  对应数据库中哪个照片的id(前端id参数)
     * @param: response 返回给前端数据( 图片下载)
     * @return: void
     * @author: Administrator
     * @since: 2019/9/27 0027
     */
    @GetMapping("/downloadFile")
    public void downloadFile(Integer id , HttpServletResponse response ) throws IOException {

        //查找对应图片二进制文件
        Photo photo = photoService.findPhotoById(id);

        //保存后图片的命名
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss") ; //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串
        //拼接,得到保存后的文件名
        String fileName = photo.getName() + ".png";

        //获取到二进制图片数据
        byte[] data = photo.getPhoto();
        //设置文件名编码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        //清除缓冲区中存在的任何数据以及状态代码和标头。如果已提交响应,此方法将抛出一个IllegalStateException。
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");

        //用于处理字符流数据 response.getWriter()
        //用于输出字符流数据或者二进制的字节流数据   response.getOutputStream()
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();


    }

 

Published 143 original articles · won praise 40 · views 20000 +

Guess you like

Origin blog.csdn.net/LemonSnm/article/details/101532573