Apache Struts 2 Documentation > Home > FAQs > How do we upload files |
You can obtain the MultipartRequestWrapper from the ServletActionContext or by utilizing the fileUpload interceptor. The fileUpload interceptor is preferred.
MultipartRequestWrapper multipartRequest = ((MultipartRequestWrapper)ServletActionContext.getRequest())
The MultipartRequestWrapper provideds access methods such as getFiles, getFile, getContentType, hasErrors, getErrors, and so forth, so that you can process the file uploaded.
_Preferred_
<form name="myForm" enctype="multipart/form-data"> <input type="file" name="myDoc" value="Browse ..." /> <input type="submit" /> </form>
public void setMyDoc(File myDoc) public void setMyDocContentType(String contentType) public void setMyDocFileName(String filename)
public File getMyDoc() public ContentType getMyDocContentType() public String getMyDocFileName()
When multiple files are uploaded by a form, the files are represented by an array.
Given:
<form name="myForm" enctype="multipart/form-data"> <input type="file" name="myDoc" value="Browse File A ..." /> <input type="file" name="myDoc" value="Browse File B ..." /> <input type="file" name="myDoc" value="Browse File C ..." /> <input type="submit" /> </form>
The Action class can define file handling methods that accept an array.
public void setMyDoc(File[] myDocs) public void setMyDocContentType(String[] contentTypes) public void setMyDocFileName(String[] fileNames)
The uploaded files can be handled by iterating through the appropriate array.
Property | Default |
---|---|
struts.multipart.parser | Commons FileUpload |
struts.multipart.saveDir | javax.servlet.context.tempdir as defined by container |
struts.multipart.maxSize | Approximately 2M |
@see struts.properties
@see org.apache.struts2.dispatcher.FilterDispatcher#doFilter(SerlvetRequest, ServletRepsonse, FilterChain)
@see org.apache.struts2.dispatcher.DispatcherUtil#wrapRequest(HttpServletRequest, SerlvetContext)
@see org.apache.struts2.dispatcher.multipart.MultipartRequestWrapper
@see org.apache.struts2.interceptor.FileUploadInterceptor