Springmvc 服務器端文件下載


轉自: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;  
    } 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM