Tutorial: Struts File Upload Example.
- By Viral Patel on December 22, 2008
- Struts, Tutorial
Let us see how we can implement file upload functionality using Apache Struts Framework. I assume you have basic knowledge about Struts and know the flow of a struts application. If you are new to struts, I suggest you to check this tutorial first: Struts Project in Eclipse.
First let us download all the required JAR files to implement file upload functionality. For this we will need common-fileupload.jar file that comes with common package of Struts.
Download common-fileupload.jar (version 1.0, size 20 kb).
Include this JAR file in your class path variable.
Now, modify the ActionForm class where you want to add File upload functionality and add following property and its getter and setter methods.
import org.apache.struts.upload.FormFile;
....
....
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
....
....
In the above code snippet, we have added an attribute file which is of type org.apache.struts.upload.FormFile. This property will contain file content and other file related information that is being upload from form.
Now add following code in your JSP page to add a file upload input.
<html:form action="/file-upload" method="post" enctype="multipart/form-data"> .... .... <html:file property="file"></html:file> .... .... </html:form>
Note that in above code we added method=”post” and enctype=”multipart/form-data” to the form. Also the name of property is same as what we mentioned in ActionForm class.
Now in the action file where you normally deal with form data, add following code to get information about the file being submitted.
//Type cast form to FileUploadForm. FileUploadForm fileForm = (FileUploadForm)form; //Get the FormFile object from ActionForm. FormFile file = fileForm.getFile(); //Get file name of uploaded file. String fileName = file.getFileName(); //Get file size of uploaded file. Integer fileSize = file.getFileSize(); //The content type of the uploaded file. String contentType = file.getContentType(); // Get InputStream object of uploaded File. InputStream inputFile = file.getInputStream();
Once you get InputStream object, you can use normal file I/O to write the file anywhere on server.
Get our Articles via Email. Enter your email address.




My self vikas working in JAVA/J2ee
How about a multiple file upload using older struts jar.
I already did a multiple file upload ( say 3 – 4 files) using just 1 upload button but looking for a better solution if possible.
I used arraylist in actionform., if you have better solution It will be appreciated.
@Mihir, I haven’t looked into that direction yet. But I feel your solution (using arraylist in actionform) seems to be correct. I will update you if I come up with something better.