根据网络url 实现web下载图片 java

本文介绍了一个基于Java的图片下载API实现方法,通过HTTP请求下载指定路径的图片,并将其返回给客户端。文章详细展示了如何处理文件读取、内容类型设置、响应头配置等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

   /*
         * 
         * 图片下载*/
         
        @RequestMapping(value = "download")
        @ResponseBody
        public void download(FileSaveModel fileSaveModel,HttpServletResponse response) throws IOException {
            BufferedInputStream dis = null;
            BufferedOutputStream fos = null;
        try {
            String fileId = fileSaveModel.getFileId();
            // path是指欲下载的文件的路径。 绝对路径
            File file = new File(fileId);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
           // String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

           // fileId = "http://30.20.110.185:22/home/pic/ad/87632cc4-2c86-44be-b3c6-f5d17abb867a.jpg";
           // 步骤1:创建 URL
            URL url = new URL (fileId);
           // 步骤2:为specificURL 获得用户名称和密码  将它们放入String并用冒号":"分开
            String userPassword = USERNAME + ":" + PASSWORD;
            // 步骤4:对字符串进行编码
            String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
            // 步骤5: 通过 URL 创建 URLConnection
            URLConnection uc = url.openConnection();
            //步骤6:为URLConnection 设置“授权”要求属性
            uc.setRequestProperty ("Authorization", "Basic " + encoding);
            URL url2 = uc.getURL();

            response.setContentType("image/jpeg");
          //  response.setHeader("Content-disposition", "attachment; filename=" +  java.net.URLEncoder.encode("aaa.jsp", "UTF-8")); 
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            
            
            response.setHeader("Content-Length", String.valueOf(uc.getContentLength()));
           
            dis = new BufferedInputStream(url2.openStream());
            fos = new BufferedOutputStream(response.getOutputStream());
            byte [] buff =  new byte[2048];
            int bytesRead;
            while(-1!= (bytesRead = dis.read(buff,0,buff.length))){
                fos.write(buff, 0, bytesRead);
            }

        } catch (IOException e) {
            logger.error("异常:", e);
            throw new BusinessException(CodeConstant.REQUEST_PROGRAM_ERROR_CODE, e+"系统异常", false);
        }finally {
            if(fos != null){
                fos.close();
            }
            if(dis != null){
                dis.close();
            }
        }
    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值