使用Struts2你有Action
s和Result
s。
所以,你需要一个Action
映射到你的链接,让我们把它叫做download_file.do
您创建的链接列表,在一个参数传递给告诉struts2的要下载的文件(这是很危险的,允许任意文件,所以也许文件名会很好)。现在
<s:iterator value="fileList">
<s:a action="download_file">
<s:property value="fileName"/>
<s:text name="my.link"/>
</a>
</s:iterator>
,在你Action
需要引领者fileName
如常。
一旦在execute
方法中拥有fileName,请打开InputStream
到File
并为其提供getter
。您可能还想要获取文件的大小以及要下载的名称。
让我们假设InputStream
的吸气剂为getFileToDownload
,吸气剂的尺寸为getFileSize
。
您需要提供内容部署一个getter,这将设置下载的文件的名称,像:
public String getContentDisposition() {
return "attachment;filename=\"" + fileName + "\"";
}
,也为MIME类型的吸气剂,像
public String getContentType() {
return "text/plain";
}
显然将MIME设置为正确的类型。
所以你的基本Action
会是这个样子
public class MyAction extends ActionSupport {
private final File baseDownloadDir = new File("somewhere");
private String fileName;
private InputStream inputStream;
private long fileSize;
@Override
public String execute() throws Exception {
/*
*This is a security hole begging to be exploited.
*A user can submit "../../../../someImportantFile"
*and potentially download arbitrary files from the server.
*You really need to do some validation on the input!
*/
final File fileToDownload = new File(baseDownloadDir, fileName);
fileSize = fileToDownload.length();
inputStream = new FileInputStream(fileToDownload);
return "downloadFile";
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getFileSize() {
return fileSize;
}
public InputStream getFileToDownload() {
return inputStream;
}
public String getContentDisposition() {
return "attachment;filename=\"" + fileName + "\"";
}
public String getContentType() {
return "text/plain";
}
}
你再返回结果的名字,让我们把它叫做downloadFile
。
在你的动作映射,你需要的是结果映射到StreamResult
,这里是一个XML例子
<result name="downloadFile" type="stream">
<param name="inputName">fileToDownload</param>
<param name="contentType">${contentType}</param>
<param name="contentLength">${fileSize}</param>
<param name="contentDisposition">${contentDisposition}</param>
<param name="contentCharSet">UTF-8</param>
<param name="allowCaching">true</param>
</result>
您可能要更改的字符集。
非常感谢您的时间。 请让我再问一个问题。在struts.xml中,是否有足够的“inputName”和“contentDisposition”参数来下载文件? –
像其他参数一样吗?唯一的_required_参数是'inputName' - 请参阅[documentation](http://struts.apache.org/release/2.3.x/docs/stream-result.html)。其他人只是让浏览器像预期的那样行事。 –