jsp实现文件下载的代码(转载)

Java代码  收藏代码
  1. OutputStream out=response.getOutputStream();  
  2.               byte by[]=new byte[500];  
  3.               File fileLoad=new File(path);  
  4.               response.reset();  
  5.               response.setContentType("application/vnd.ms-excel");  
  6.               response.setHeader("content-disposition","attachment; filename=text.xls");  
  7.               long fileLength=fileLoad.length();  
  8.               String length1=String.valueOf(fileLength);  
  9.               response.setHeader("Content_Length",length1);  
  10.               FileInputStream in=new FileInputStream(fileLoad);  
  11.               int n;  
  12.               while((n=in.read(by))!=-1){  
  13.                out.write(by,0,n);  
  14.               }  
  15.                 
  16.               in.close();  
  17.               out.flush();  

以上代码以下载excel为例,各种文件的下载大体相同只需改变相应的contentType即可。
其中response.setContentType()的String参数及对应类型为

Java代码 BMP

GIF JPEG TIFF DCX PCX HTML TXT XML AFP PDF RTF MSWORD MSEXCEL MSPOWERPOINT WORDPERFECT WORDPRO VISIO FRAMEMAKER LOTUS123" quality="high" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> 收藏代码

  1. <option   value="image/bmp">BMP</option>    
  2. <option   value="image/gif">GIF</option>    
  3. <option   value="image/jpeg">JPEG</option>    
  4. <option   value="image/tiff">TIFF</option>    
  5. <option   value="image/x-dcx">DCX</option>    
  6. <option   value="image/x-pcx">PCX</option>    
  7. <option   value="text/html">HTML</option>    
  8. <option   value="text/plain">TXT</option>    
  9. <option   value="text/xml">XML</option>    
  10. <option   value="application/afp">AFP</option>    
  11. <option   value="application/pdf">PDF</option>    
  12. <option   value="application/rtf">RTF</option>    
  13. <option   value="application/msword">MSWORD</option>    
  14. <option   value="application/vnd.ms-excel">MSEXCEL</option>    
  15. <option   value="application/vnd.ms-powerpoint">MSPOWERPOINT</option>    
  16. <option   value="application/wordperfect5.1">WORDPERFECT</option>    
  17. <option   value="application/vnd.lotus-wordpro">WORDPRO</option>    
  18. <option   value="application/vnd.visio">VISIO</option>    
  19. <option   value="application/vnd.framemaker">FRAMEMAKER</option>    
  20. <option   value="application/vnd.lotus-1-2-3">LOTUS123</option>  
原文地址:https://www.cnblogs.com/haw2106/p/7198699.html