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

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();
                }
            }
        }
    }
posted @   小昕昕  阅读(142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示