struts2中文件下载的注意事项

配置文件如下:

<package name="download" extends="struts-default" namespace="/">
<default-action-ref name="download"></default-action-ref>
<action name="download" class="com.inspur.action.FileDownloadAction" method="download">
<param name="inputPath">\upload\8.gif</param>
<result name="success" type="stream">
<param name="contentType">image/gif</param>
<param name="inputName">targetFile</param>
<param name="contentDisposition">filename="struts.gif"</param>
<param name="bufferSize">4096</param>
</result>
<result name="login">/download.jsp</result>
</action>
</package>

使用默认的下载支持拦截器download,此次success不在是type默认的jsp文件类型而变为stream类型这样在配置stream类型的结果集中要配置四个属性:contentType文件类型,inputName下载文件的输入流接口对应的值为targetFile该属性是在action中的一个属性,此次在配置文件中获得action中的属性值,必须在actgion中提供targetFile的get/set访问器。contentDisposition下载后保存的文件的文件名。bufferSize下载的缓冲区大小。在配置文件中的inputPath是用来动态配置在action中的属性即下载文件的入口。

下载的action代码如下:

package com.inspur.action;

import java.io.InputStream;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport {
private String inputPath;
private InputStream targetFile;

public String getInputPath() {
return inputPath;
}

public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public InputStream getTargetFile() throws Exception {
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);

}
public void setTargetFile(InputStream targetFile){
this.targetFile=targetFile;

}
public String download(){
ActionContext act=ActionContext.getContext();
Map session=act.getSession();
String title=(String)session.get("title");
if(title!=null&&title.equals("lzhq")){

return SUCCESS;
}else{
act.put("tip", "please set the title is lzhq");

return LOGIN;
}




}

}

通常在文件的下载过程中要求有下载权限,所以在action代码中添加权限校验支持,如果下载权限不够则跳转到 input逻辑视图,并显示提示信息。

原文地址:https://www.cnblogs.com/moonfans/p/3027899.html