文件下载-java

public static void downLoadFile(HttpServletRequest request,HttpServletResponse response,String fullPath) throws IOException {
		OutputStream outp = response.getOutputStream();
		File file = new File(fullPath);
		if (file.exists()) {
			//设置请求以及响应的内容类型以及编码方式
			response.setContentType("application/x-msdownload; charset=utf-8"); 
			String agent = (String)request.getHeader("USER-AGENT");  
			
			if (agent != null &&agent.toLowerCase().indexOf("firefox") > 0)  {
				response.setHeader("Content-Disposition", "attachment; filename=" +  new String(filedisplay.getBytes("UTF-8"), "ISO8859-1"));//firefox浏览器  
			}else {
				//if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)  
				response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filedisplay, "UTF-8"));//IE浏览器
			}
			FileInputStream in = null;
			try {
				outp = response.getOutputStream();
				//获取文件输入流
				in = new FileInputStream(fullPath);
				byte[] b = new byte[1024];
				int i = 0;
				//将缓冲区的数据输出到客户浏览器
				while ((i = in.read(b)) > 0) {
					outp.write(b, 0, i);
				}
				outp.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					in.close();
					in = null;
				}
				if (outp != null) {
					outp.close();
					outp = null;
					response.flushBuffer();
				}
			}
		} else {
			outp.write("文件不存在!".getBytes("utf-8"));
		}
	}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页