1. 程式人生 > >java web 下載檔案 瀏覽器彈出下載框

java web 下載檔案 瀏覽器彈出下載框

前端js檔案:window.open("feeWarning/excelQfAll");//訪問後臺springmvc中的excelQfAll方法得到下載的資源

採用的springmvc框架

後臺java檔案:

public void excelQfAll(HttpServletRequest request,HttpServletResponse response) {
String filename=request.getSession().getServletContext().getRealPath("/static/email/");
String filenameZip=filename+"\\email.zip";

try {
response.setContentType("application/x-execl"); 
response.setHeader("Content-Disposition", "attachment;filename=" + new String(("email.zip").getBytes(), "UTF-8"));
     //讀取檔案  
       InputStream in = new FileInputStream(filenameZip);  
ServletOutputStream outputStream = response.getOutputStream();
       //寫檔案  
       int b;  
       while((b=in.read())!= -1)  
       {  
        outputStream.write(b);  
       }  
         
       in.close();  
       outputStream.close(); 
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}