SpringMVC从网络地址下载文件

例如有这么个地址:http://xxx/abc,直接把这个地址放到浏览器后,只能打开图片,不能下载,这个时候,我们需要做一定的处理后才能下载该地址的文件。
我使用的框架是SpringMVC,所以这里的示例代码也是在SpringMVC下验证通过的。

@RequestMapping(value = "/download",produces="application/octet-stream")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,@RequestParam("path")String path) {
        if(StringUtils.isBlank(path)){
            return;
        }
        try {
            URL url = new URL(path);
            //文件名拼接
            String[] fileNames = path.split("/");
            String fileName = fileNames[fileNames.length-1].concat(".jpg");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            int len;
            // 输出的文件流s
            OutputStream os = response.getOutputStream();
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.flush();
            // 完毕,关闭所有链接
            os.close();
            is.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
示例代码解释如下:
1,produces="application/octet-stream"
这是response的content type类型,常见的类型有下面这些:

text/html :以html的格式返回

application/xml;charset=UTF-8 :以xm格式返回

application/json;charset=UTF-8 :以json格式返回

application/octet-stream :以流的形式返回

……

2,response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

response的header中,Content-Disposition:attachment 以附件形式下载文件;Content-Disposition:inline 在网页中内嵌打开,这里一定是针对可内嵌显示的类型,例如"image/jpeg","image/png"等。

3,OutputStream os = response.getOutputStream();

这里借助response的SevletOutPutStream把流输出到浏览器。

示例中,由于我的url源提供的都是jpeg的图片,所以我给他加了扩展名,方便下载后直接用图片查看工具打开。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值