struts2文件下载

	public String download(){

			// 文件下载目录路径 

			String downloadFile =ServletActionContext.getServletContext().getRealPath("downloadtemp")
			  +"/"+downloadFileName; 

			File file = new File(downloadFile); 
			String filename = file.getName(); 


			// 以流的形式下载文件。 
			try {
				InputStream fis = new BufferedInputStream(new FileInputStream(downloadFile));
				try {
					byte[] buffer = new byte[fis.available()];
					fis.read(buffer); 
					fis.close(); 
					// 清空response 
					ActionContext ctx = ActionContext.getContext(); 
					HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);        
					response.reset(); 
					// 设置response的Header 
					response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); 
					response.addHeader("Content-Length", "" + file.length()); 
					OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); 
					response.setContentType("application/octet-stream"); 
					toClient.write(buffer); 
					toClient.flush(); 
					toClient.close(); 
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return null; 

	}

 

你可能感兴趣的:(struts2)