文件下載—SSM框架文件下載


1、准備上傳下載的api組件

<dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
</dependency> 
<dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
 
2、編寫前台上傳表單
<body>
請點擊下載:<a href="user/download?filename=moni.jpg">moni.jpg</a>
</body>
 
3、編寫controller層( 在conreoller層拼接附件名字和所在文件夾位置(path),創建輸出流直接寫入response中
  /**
         * 文件下載
         * @throws IOException 
         */
        @RequestMapping(value="/download",method=RequestMethod.GET)
        public void download(@RequestParam(value="filename")String filename,
                HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            //模擬文件,myfile.txt為需要下載的文件  
            String path = request.getSession().getServletContext().getRealPath("statics\\upload")+"\\"+filename;  
            //獲取輸入流  
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
            //轉碼,免得文件名中文亂碼  
            filename = URLEncoder.encode(filename,"UTF-8");  
            //設置文件下載頭  
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
            //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型    
            response.setContentType("multipart/form-data");   
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
            int len = 0;  
            while((len = bis.read()) != -1){  
                out.write(len);  
                out.flush();  
            }  
            out.close();  
        }

 


免責聲明!

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



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