这是一个文件下载的jsp界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>首页</title> </head> <body> <html:link action="/RegisterUIAction">注册</html:link> <html:link action="/EditUserUI">修改用户信息</html:link> <html:link action="/UploadFileUI">上传文件</html:link> <html:link action="/DownFileAction">下载文件</html:link> </body> </html>然后在struts-config配置文件中配置一把
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <action-mappings> <action path="/DownFileAction" type="cn.lfd.web.action.DownFileAction" scope="request" validate="false" ></action> <action path="/UploadFileUI" forward="/WEB-INF/jsp/upload.jsp"></action> </action-mappings> </struts-config>最后新建一个DownFileAction 继承 DownloadAction就可以实现文件的下载了
package cn.lfd.web.action; import java.io.File; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DownloadAction; public class DownFileAction extends DownloadAction { @Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //拿到ServletContext对象来获取要下载的文件的真实路径 ServletContext context = request.getSession().getServletContext(); String path = context.getRealPath("/download/1.png"); //通过真实路径构建一个File对象 File file = new File(path); //设置好response的一些头和文件的文件名 response.setHeader("content-disposition", "attachment;filename="+file.getName()); //通过返回FileStreamInfo对象来把数据打给浏览器 return new DownloadAction.FileStreamInfo("image/jpg", file); } }