关于文件下载的小例子

一个关于文件下载的简单例子,相当简洁,是通过servlet进行调用

String realPath=request.getSession().getServletContext().getRealPath("/");
			String filePath = realPath+ "file\\download\\list.zip";
			try {
				if(!"".equals(filePath)){ 
					File file=new File(filePath); 
					if(file.exists()){ 
						response.setContentType("application/octet-stream;charset=UTF-8");
						response.setHeader("Content-disposition","attachment;filename="+ new String( file.getName().getBytes()));//设置头部信息 
						RequestDispatcher dispatcher = request.getRequestDispatcher("file\\upload\\list.zip");
						if (dispatcher != null) {
							dispatcher.forward(request, response);
						}
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

   js中调用可以如下,不能使用ajax

写道
function dwonloadFile(path){
var basePath = $("#base").val();
var param = "flag=downloadFile&fileId="+path;
document.location.href=basePath+"?"+param;
}

 

你可能感兴趣的:(文件下载)