您的位置:首页 > 编程语言 > Java开发

Struts2文件下载(灵活控制MIME、FILENAME)

2017-06-02 00:00 375 查看
下载流程概览: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;
}

}

说明:

在下载的Action中,必须有个InputStream类型的field和对应的get方法。

下载时方便,将文件名、MIMETYPE都写在了Action中。

STEP02 编写配置文件

<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>

解释说明:

为了获取到MIMETYPE,利用了ServletContext的方法。所以必须获得ServlerContext这个对象。本例子中采用DI的方法,有Struts2在运行时注入。

为了能在HTTP Response中使用到MIMETYPE,所以在Action中提供了对应的get方法,以供OGNL表达式需要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Struts