java 下载url图片并导出到前端

1、controller


    /**
     * 下载二维码
     * @param qrId
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getImg")
    public void getImg(@RequestParam("qrId") String qrId, HttpServletRequest request, HttpServletResponse response) throws IOException {

          roomQrService.getImg(qrId,request,response);

    }

2、service

    /**
     * 下载二维码
     * @param qrId
     * @return
     * @throws IOException
     */
    void getImg( String qrId, HttpServletRequest request, HttpServletResponse response);

3、serviceImpl

 /**
     * 下载二维码
     * @param qrId
     * @return
     * @throws IOException
     */
    @Override
    public void getImg(String qrId, HttpServletRequest request, HttpServletResponse response){
        
        //图片URL地址
        String imgUrl="";
        //图片名称
        String filename="";
        String path =filename;
        InputStream inputStream = null;
        OutputStream out = null;
        File file = null;
        try {
            file = new File(path);
            URL url =new URL(imgUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
//			conn.setConnectTimeout(1000);//超时提示1秒=1000毫秒
            FileUtils.copyURLToFile(url, file);
//			inputStream =  conn.getInputStream();//获取输出流

            response.setContentType("png/jpg");
            response.setHeader("Content-Disposition", "attachment" + ";filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            byte[] bytes = new byte[(int)file.length()];
            inputStream = new FileInputStream(file);
            out = response.getOutputStream();
            out.write(bytes, 0, inputStream.read(bytes));
        }catch (Exception e) {


        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (file != null && file.exists()) {
                file.delete();
            }
        }

    }

4、效果

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值