例如有这么个地址: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的图片,所以我给他加了扩展名,方便下载后直接用图片查看工具打开。
 
