随笔(十六)『通过图片URL下载图片-Java』

发布时间 2023-04-11 15:41:56作者: 小昕昕
public void downloadInvitationImage(Map<String, Object> params, HttpServletResponse response)  {
        String visitPath = (String) params.get("visitPath");  // 公网url
       
        ServletOutputStream sos = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try {
            URL url = new URL(visitPath); // 构造url
            HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // 开启连接
            connection.setRequestMethod("GET"); // 设置get请求
            is = connection.getInputStream(); // 获取输入流
            bis = new BufferedInputStream(is); // 创建带缓存的输入流
            byte[] bytes = new byte[8 * 1024]; // 8kb的字节数组,每次最多读取8kb数据
            int len = 0;

            String suffix = visitPath.substring(visitPath.lastIndexOf(".")); // 图片后缀

            String fileName = "图片名称";
            sos = response.getOutputStream(); // 获取响应输出流
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + suffix);

            while ((len = bis.read(bytes)) != -1) { // 读取到数据就写出去
                sos.write(bytes, 0, len);
            }
        }catch (IOException e) {
            throw new RenException("下载出错");
        }finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }