`
java-mans
  • 浏览: 11519046 次
文章分类
社区版块
存档分类
最新评论

struts2文件下载

 
阅读更多

Struts2可以提供中文名文件下载的支持,HTML页面代码如下:

<body>
<h1>Struts2的文件下载</h1>
<ul>
<li>
下载中文名称的文件:<a href="download.action">下载中文名称文件</a>
</li>
</ul>
</body>

Action代码如下:

package com.annlee.upload;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {
//该属性是依赖注入的属性,可以在配置文件中动态指定该属性值
private String inputPath;

//依赖注入该属性值的set方法

public String getInputPath() {
return inputPath;
}

public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}

public String execute() throws Exception{
return this.SUCCESS;
}

/**
* 下载用的action应该返回一个InputStream实例,该方法对应在result里的inputName属性值为targetFile
*/
public InputStream getTargetFile() throws Exception{
return ServletActionContext.getServletContext().getResourceAsStream(this.inputPath);
}

}

struts.xml文件中的配置如下:

<action name="download" class="com.annlee.upload.DownloadAction">
<!-- 指定被下载资源的位置 -->
<param name="inputPath">/images/struts-中.zip</param>
<!-- 配置结果类型为stream的结果 -->
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>

<paramname="inputName">inputStream</param> <param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>

从上面可以看到配置该action的关键是需要配置一个类型为stream的结果,配置时要指定以下四个属性:

contentType, inputName, contentDisposition, bufferSize因为stream结果类型的逻辑视图是返回给客户端一个输入流,因此不需要指定location属性。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics