我想实现一个自定义的 Struts2 MultiPartRequest,通过设置进度监听器来实现渐进式文件上传。
我通过实现属于 Core-struts2 的 MultiPartRequest 编写了自定义 FileUploadMultipartRequest。
public class FileUploadMultipartRequest implements MultiPartRequest {
static final Log log = LogFactory.getLog(MultiPartRequest.class);
// maps parameter name -> List of FileItem objects
private Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();
// maps parameter name -> List of param values
private Map<String, List<String>> params = new HashMap<String, List<String>>();
// any errors while processing this request
private List<String> errors = new ArrayList<String>();
private long maxSize;
@Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE)
public void setMaxSize(String maxSize) {
this.maxSize = Long.parseLong(maxSize);
}
/**
* Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
* multipart classes (see class description).
*
* @param saveDir the directory to save off the file
* @param servletRequest the request containing the multipart
* @throws java.io.IOException is thrown if encoding fails.
*/
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
DiskFileItemFactory fac = new DiskFileItemFactory();
// Make sure that the data is written to file
fac.setSizeThreshold(0);
if (saveDir != null) {
fac.setRepository(new File(saveDir));
}
ProgressMonitor monitor = null;
// Parse the request
try {
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setSizeMax(maxSize);
monitor = new ProgressMonitor();
upload.setProgressListener(monitor);
servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor);
...
}
}
...
}
并在 struts.xml 中设置属性
<constant name="struts.multipart.parser" value="com.cloudlabz.service.web.action.FileUploadMultipartRequest " />
<constant name="struts.multipart.maxSize" value="504857600" />
虽然我已经在 struts.xml 中设置了自定义 MultipartRequestHandeler,但 Struts 2 仍然执行自己的 JakartaMultiPartRequest (Struts2 默认解析器来处理多部分请求)类,而不是我的自定义 FileUploadMultipartRequest 类。
请建议我一些解决方法。
最佳答案
如果您使用的是 Struts 2 版本 2.1.8 + 则在这种情况下您需要将 struts.multipart.parser
更正为 struts.multipart.handler
某些内容喜欢
<constant name="struts.multipart.handler"
value="com.cloudlabz.service.web.action.FileUploadMultipartRequest" />
在您的情况下,jakarta
将执行具有相同 bean 定义的 struts-plugin.xml
配置文件的操作。
对于早期版本,似乎有一种方法,创建一个插件,例如MycustomFileUpload
。放入 WEB-INF/lib 下,确保 jar 文件应包含类和 struts-plugin.xml 文件。
将以下条目添加到struts-plugin.xml
<struts>
<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest"
name="jakartax"
class="com.cloudlabz.service.web.action.FileUploadMultipartRequest"
scope="default" />
</struts>
在这种情况下,您不需要在 struts.xml
文件中定义常量。希望这对您有用。
关于file-upload - 如何使用自定义struts.multipart.parser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8937986/