我需要执行非常基本的文件上传操作,但在我的情况下,文件上传拦截器不会调用setter方法。
我查过类似问题的解答like this在 stackoverflow 上,但他们没有解决我的问题。
请让我知道我在代码中犯了什么错误。
Action 类
public class ResultFileUploadAction extends ActionSupport {
private File upload;
private String uploadFileName;
private String uploadContentType;
private Logger logger = Logger.getRootLogger();
@Override
public String execute() throws Exception {
logger.info("ResultFileUploadAction->execute");
String destPath = "C:/work/";
try {
System.out.println("Src File name: " + upload);
System.out.println("Dst File name: " + uploadFileName);
File destFile = new File(destPath, uploadFileName);
FileUtils.copyFile(upload, destFile);
} catch (IOException e) {
e.printStackTrace();
return ERROR;
}
return super.execute();
}
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
}
Jsp文件
<body>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
Struts.xml
<interceptors>
<interceptor name="fileupload"
class="org.apache.struts2.interceptor.FileUploadInterceptor"></interceptor>
<interceptor name="servletConfig"
class="org.apache.struts2.interceptor.ServletConfigInterceptor" />
<interceptor name="authenticationinterceptor"
class="interceptors.common.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="securestack">
<interceptor-ref name="authenticationinterceptor"></interceptor-ref>
<interceptor-ref name="servletConfig"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="upload" class="actions.result.ResultFileUploadAction"
method="execute">
<interceptor-ref name="securestack"></interceptor-ref>
<interceptor-ref name="fileupload"></interceptor-ref>
<result name="success" type="dispatcher">/AddResultBullk.jsp</result>
</action>
由于不会调用 setter ,因此我在 execute()
中得到 NPE
。
最佳答案
如 fileUpload
拦截器文档中所述:
It adds the following parameters, where [File Name] is the name given to the file uploaded by the HTML form. [fileName, contentType]
当使用拦截器堆栈时,总是有两种攻击计划:
- 尝试非自定义堆栈
- 除非您确切地知道为什么这样做以及在做什么,否则不要弄乱堆栈。
此外,配置为几乎不使用拦截器的操作(如您的操作)几乎总是值得怀疑的,因为它们消除了大部分框架功能。参数对于基本上每个基于表单的操作来说尤其关键。
关于java - 文件上传拦截器不调用setter方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23767586/