码迷,mamicode.com
首页 > 编程语言 > 详细

Springmvc 服务器端文件下载

时间:2017-09-19 03:42:50      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:open   https   error   iso   header   直接   java   cte   character   

转自:http://blog.csdn.net/boneix/article/details/51303280

业务场景:点击下载后直接保存而不是打开

解决代码:前端传入url

/** 
     * 返回流 
     *  
     * @param requestMap 请求参数 
     * @param response 返回对象 
     */  
    @RequestMapping(value = "/file2Stream", method = RequestMethod.GET)  
    public void file2Stream(@Json Map<String, Object> requestMap, HttpServletResponse response) {  
        InputStream iStream = null;  
        OutputStream outStrem = null;  
        try {  
            String url = String.valueOf(requestMap.get("url"));  
            iStream = getFileStream(url);  
            String fileName = String.valueOf(requestMap.get("fileName"));  
            fileName = new String(fileName.getBytes(), "ISO8859-1");  
            response.setCharacterEncoding("utf-8");  
            response.setContentType("multipart/form-data");  
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");  
            outStrem = response.getOutputStream();  
            outStrem.write(StreamUtils.getBytes(iStream));  
            outStrem.flush();  
        } catch (Exception e) {  
            LOG.error("ProductSalesRecommendController.file2Stream  error | ({})", e);  
        }finally {  
            if(iStream != null){  
                try {  
                    iStream.close();  
                    iStream = null;  
                } catch (IOException e) {  
                    LOG.error("file2Stream.InputStream.close  error | ({})", e);  
                }  
            }  
            if(outStrem != null){  
                try {  
                    outStrem.close();  
                    outStrem = null;  
                } catch (IOException e) {  
                    LOG.error("file2Stream.OutputStream.close  error | ({})", e);  
                }  
            }  
        }  
    }
/** 
     * HttpClient获取网络路径的文件流 
     *  
     * @param url 链接字符串 
     * @return InputStream 
     * @throws IllegalStateException 
     * @throws IOException 
     */  
    private InputStream getFileStream(String url)  
            throws IllegalStateException, IOException {  
        InputStream inStream = new URL(url).openStream();  
        return inStream;  
    } 

  

Springmvc 服务器端文件下载

标签:open   https   error   iso   header   直接   java   cte   character   

原文地址:http://www.cnblogs.com/tv151579/p/7546103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!