Struts2对文件的下载做了很优雅的处理,配置起来很简单,使用也很方便。
在本文中,你将学会最基础的download案例,和最优雅的download案例。
优雅之处:
1、不适用特定的new File加载文件。
2、文件名灵活,无需写死。
3、MimeType灵活,无需写死。
如主页的说明--“非技术流”, 表达不精确的地方,各位包涵。废话不说,上货!
环境: JDK6update16 EclipseJEE 3.4.2 Struts2.1.8
下载流程概览:
HttpRequest ---> DownloadAction ---> SUCCESS Result --> 输出流
STEP01 写一个DownloadAction
package study.action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport implements
ServletContextAware {
private static final long serialVersionUID = 1L;
private ServletContext context;
private String filename;
private String mimeType;
private InputStream inStream;
@Override
public String execute() throws Exception {
mimeType = context.getMimeType(filename);
return SUCCESS;
}
public InputStream getInStream() {
inStream = context.getResourceAsStream("/doc/" + filename);
if (inStream == null) {
inStream = new ByteArrayInputStream("Sorry,File not found !"
.getBytes());
}
return inStream;
}
public String getMimeType() {
return mimeType;
}
public void setFilename(String filename) {
try {
this.filename = new String(filename.getBytes("ISO8859-1"),"GBK");
} catch (UnsupportedEncodingException e) {
}
}
public String getFilename() {
try {
return new String(filename.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
return this.filename;
}
}
@Override
public void setServletContext(ServletContext context) {
this.context = context;
}
}
说明:
1、在下载的Action中,必须有个InputStream类型的field和对应的get方法。
2、下载时方便,将文件名、MIMETYPE都写在了Action中。
然后,配合Result类型:
<action name="download" class="study.action.DownloadAction">
<result type="stream">
<param name="contentType">${mimeType}</param>
<param name="inputName">inStream</param>
<param name="contentDisposition">attachment;filename="${filename}"</param>
</result>
</action>
最后,看图:
看看中文问题(具体的解决办法没有,这种只是在我的机子上可以。。。)
解释说明:
1、为了获取到MIMETYPE,利用了ServletContext的方法。所以必须获得ServlerContext这个对象。本例子中采用DI的方法,有Struts2在运行时注入。
2、为了能在HTTP Response中使用到 MIMETYPE,所以在Action中提供了对应的get方法,以供OGNL表达式需要。