通过response输出流实现下载功能

<%//download.jsp%>
<%@ page language="java" import="java.util.*,java.io.*"
	pageEncoding="GBK"%>
<%
	response.setCharacterEncoding("utf-8");
	String path = request.getParameter("path");//get path
	path = new String(path.getBytes("iso-8859-1"));//parameter must be ISO-8859-1
	File file = new File(path);
	InputStream in = new FileInputStream(file);
	OutputStream os = response.getOutputStream();//get response outputStream
	response.addHeader("Content-Disposition", "attachment;filename="
			+ new String(file.getName().getBytes("gbk"), "iso-8859-1"));
	response.addHeader("Content-Length", file.length() + "");
	response.setContentType("application/octet-stream");
	int data = 0;
	while ((data = in.read()) != -1) {//-1 when reach the end
		os.write(data);
	}
	os.close();
	in.close();
%>

上面的代码将获取的文件通过response.getOutputStream输出。

	HREF="download.jsp?path=<%=getServletContext().getRealPath("test.jpg")%>">
	
上面的代码嵌入到某个JSP中,点击图片,执行download.jsp方法,并把文件的路径以参数的形式传送过去。其中getServletContext().getRealPath() 获取到WebRoot根目录下,可以通过拼接路径获得WebRoot下的子目录。

你可能感兴趣的:(JavaEE)