分类目录归档:struts

struts2上传大小为0的文件问题解决

当struts上传大小为0kb的文件的时候,struts默认当文件不存在,后台接收的文件file.exist()的值为false;

我使用的struts版本为:2.1.8.1;其他版本可能会没有这个问题,未做测试;

参考:Struts 2.3.1 GA 版发布

  • [WW-3562] – FileUploadInterceptor: File not uploaded when file is empty (0 bytes)

struts 配置有个属性struts.multipart.parser,该属性指定处理multipart/form-data的MIME类型(文件上传)请求的框架,该属性支持cos、pell和jakarta等属性值,即分别对应使用cos的文件上传框架、pell上传及common-fileupload文件上传框架。该属性的默认值为jakarta。

为jakarta时候,如果上传的文件大小为0kb,则struts读取文件则是不存在的:

When not selecting any file to upload in a file input, Struts does not ignore the 0 byte file
returned by jakarta FileUpload.
This means that a file is injected in the action even if nothing was uploaded.

In webwork the check was done in the constructor of  com.opensymphony.webwork.dispatcher.multipart.JakartaMultiPartRequest:

else if (item.getSize() == 0) {
log.warn("Item is a file upload of 0 size, ignoring");
}

In struts the parsing of the request moved from the constructor to a parse method but the
above check disappeared.

Additionally this behaviour is inconsistant with the "pell" implementation that ignores 0
byte files.

--
This message is automatically generated by JIRA.

这里是STRUTS_MULTIPART_PARSER的官方文档说明:

STRUTS_MULTIPART_PARSER

public static final String STRUTS_MULTIPART_PARSER

The org.apache.struts2.dispatcher.multipart.MultiPartRequest parser implementation for a multipart request (file upload)

See Also:
Constant Field Values

注意  如果需要使用cos或者pell的文件上传方式,则应该将对应的JAR文件复制到Web应用中。
例如,使用cos上传方式,则需要自己下载cos框架的JAR文件,并将该文件放在WEB-INF/lib路径下。但是我测试仍然为通过,原因未知。

解决办法2:

if (!srcFile.exists()) {
 try {
   destFile.createNewFile();//创建空文件
 } catch (IOException e) {
   LogUtil.error(e);
   return;
 }
} else {
//文件操作
}

参考:

struts2 的struts.properties配置详解

http://www.iteye.com/problems/19141