在jsp中有一个a标签 ,当用户点击a标签的时候下载文件。

我们采用href属性直接指向一个服务器地址,只要链接的文件存在,就会给出弹出保存对话框.

点击a标签 先执行onclick事件,再请求href中指向的地址。

前端jsp:

<a href="#" οnclick="javascript:downloadtest('${app.id}')"  id="pluginurl"  style="color: #83AFE2;text-decoration:underline;"></a>

然后在js中:

 function downloadtest(id){
var url = "<%=request.getContextPath()%>/app/download" + "/" + id;
$("#pluginurl").attr("href",url);
}


后台java代码: 我的是springmvc


[java] view plaincopy

  1. /** 

  2.      * 下载文件 

  3.      * @param id appid 

  4.      * @param response 

  5.      */  

  6.     @RequestMapping(value="/download/{id}")  

  7.     public void download(@PathVariable String id, HttpServletResponse response){  

  8.         String filepath = "";  

  9.         Result result = appService.getAppById(id);  

  10.         App app = (App) result.getMap().get("app");  

  11.         if(app == null){  

  12.             return;  

  13.         }  

  14.         filepath = app.getUrl();  

  15.           

  16.         File file = new File(filepath);  

  17.         InputStream inputStream = null;  

  18.         OutputStream outputStream = null;  

  19.         byte[] b= new byte[1024];  

  20.         int len = 0;  

  21.         try {  

  22.             inputStream = new FileInputStream(file);  

  23.             outputStream = response.getOutputStream();  

  24.               

  25.             response.setContentType("application/force-download");  

  26.             String filename = file.getName();  

  27.             filename = filename.substring(36, filename.length());  

  28.             response.addHeader("Content-Disposition","p_w_upload; filename=" + URLEncoder.encode(filename, "UTF-8"));  

  29.             response.setContentLength( (int) file.length( ) );  

  30.               

  31.             while((len = inputStream.read(b)) != -1){  

  32.                 outputStream.write(b, 0, len);  

  33.             }  

  34.         } catch (Exception e) {  

  35.             e.printStackTrace();  

  36.         }finally{  

  37.             if(inputStream != null){  

  38.                 try {  

  39.                     inputStream.close();  

  40.                     inputStream = null;  

  41.                 } catch (IOException e) {  

  42.                     e.printStackTrace();  

  43.                 }  

  44.             }  

  45.             if(outputStream != null){  

  46.                 try {  

  47.                     outputStream.close();  

  48.                     outputStream = null;  

  49.                 } catch (IOException e) {  

  50.                     e.printStackTrace();  

  51.                 }  

  52.             }  

  53.         }  

  54.     }  


注意:response.addHeader("Content-Disposition","p_w_upload; filename=" + URLEncoder.encode(filename, "UTF-8"));