Struts2.1文件下载

    技术2025-07-12  18

    1.编写静态界面

    <html> <head> <title>Struts2.1文件下载</title> </head> <body> <a href="download.action" mce_href="download.action">下载一个压缩包</a> </body> </html>

    2.编写action

    package cdl; import java.io.InputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class DownloadAction extends ActionSupport { private String inputPath; public String getInputPath() { return inputPath; } public void setInputPath(String inputPath) { this.inputPath = inputPath; } public InputStream getTargetFile() throws Exception { return ServletActionContext.getServletContext().getResourceAsStream( this.getInputPath()); } @Override public String execute() throws Exception { return SUCCESS; } }

    3.编写struts.xml文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="cdl" extends="struts-default"> <action name="download" class="cdl.DownloadAction"> <!-- 定义下载的物理资源 --> <param name="inputPath">/upload/cdl.zip</param> <result name="success" type="stream"> <!-- 指定下载文件的类型 --> <param name="contentType">application/zip</param> <!-- 指定由getTargetFile()方法返回下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="cdl.zip"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> </action> </package> </struts>

    附:

    当然,完成这些的前提是先配置struts2的开发环境。

    最新回复(0)