JAVAweb 前端点击按钮下载远程图片

想法

记录一下自己做这种需求的时候遇到的一些坑及方案 备查

前端如通过a标签js下载"

<a href="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558084900036&di=ae072a03a93c4739b6bdf63a030eed48&imgtype=0&src=http%3A%2F%2Fpic.downcc.com%2Fupload%2F2015-1%2F201512094354.jpg" download="logo.png">下载图片</a>

这种通过a标签download有些浏览器不支持
有时候也会出现在项目中点击出这张图片

在我实际操作中能下载,但是下载下来的图片不能使用

JAVA代码

前端按钮

<a href="/download?fileId=图片地址" id="download" ><button type="button" class="btn btn-default" >另存为</button></a>

不加A标签会导致前端响应为一张图片而无法下载

后台代码

@RequestMapping(value = "/download")
@ResponseBody
public void download(HttpServletResponse response,String fileId) throws IOException {
    BufferedInputStream dis = null;
    BufferedOutputStream fos = null;
    try {
        System.err.println("fileid:"+fileId);
        // path是指欲下载的文件的路径。 绝对路径
        File file = new File(fileId);
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
        // 步骤1:创建 URL
        URL url = new URL (fileId);
        // 步骤2:为specificURL 获得用户名称和密码  将它们放入String并用冒号":"分开
        // 步骤4:对字符串进行编码
        // 步骤5: 通过 URL 创建 URLConnection
        URLConnection uc = url.openConnection();
        //步骤6:为URLConnection 设置“授权”要求属性
        uc.setRequestProperty ("Authorization", "Basic " );
        URL url2 = uc.getURL();
        response.setContentType("image/jpeg");
        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) {
        throw new IOException();
    }finally {
        if(fos != null){
            fos.close();
        }
        if(dis != null){
            dis.close();
        }
    }
}`
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值