Tapestry4实现文件导出功能

@InjectObject("service:tapestry.globals.HttpServletResponse")
public abstract HttpServletResponse getHttpServletResponse();

String filePath=null,fileName=null;
	try{
			filePath=getDocFilePath();
			fileName = getTitle() +"."+"doc";
			getHttpServletResponse().setContentType(
					"application/x-msdownload;charset=GBK");
			filePath = ReadProperty.getInstance().getType("doc")+filePath;
			File file = new File(filePath);
			if (file.exists()) {
				try {
					FileInputStream fileIn = new FileInputStream(file);
					long l = file.length();
					byte[] b = new byte[1024];
					int k = 0;
					String str = new String(fileName.getBytes("gb2312"),"iso-8859-1");

					getHttpServletResponse().setHeader(
							"Content-Disposition",
							"attachment;" + " filename=\"" + str + "\"");

					while ((long) k < l) {
						int j = fileIn.read(b, 0, 1024);
						k += j;
						getHttpServletResponse().getOutputStream()
								.write(b, 0, j);
					}
					getHttpServletResponse().getOutputStream().flush();
					fileIn.close();
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("该文件不存在。");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}	


附:servlet/jsp 获取绝对路径和相对路径
servlet中获得项目绝对路径
String filePath=this.getServletConfig().getServletContext().getRealPath("/");

根目录所对应的绝对路径:request.getServletPath();

文件的绝对路径 :request.getSession().getServletContext().getRealPath(request.getRequestURI())

当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");

ServletContext对象获得几种方式:

Javax.servlet.http.HttpSession.getServletContext()

Javax.servlet.jsp.PageContext.getServletContext()

Javax.servlet.ServletConfig.getServletContext()

文件的绝对路径 :request.getSession().getServletContext().getRealPath(request.getRequestURI())

当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");

你可能感兴趣的:(Web,jsp,servlet,J#,tapestry)