欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浏览器下载文件

程序员文章站 2022-07-14 09:39:14
...
      /**
	 * 下载文件
	 * 
	 * @param basePath
	 * @throws IOException
	 */
	private void downLoadFile(String basePath) throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		File zipFile = new File(basePath + ".zip");
		try {
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(
					zipFile.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(zipFile.getName().getBytes("utf-8")));
			response.addHeader("Content-Length", "" + zipFile.length());
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			PrintWriter out = response.getWriter();
			out.print("<script>alert('down file err');</script>");
			out.close();
		}
	}