File Upload Example with Struts

With is example we will learn how to upload a file to the server using struts 1 and perform some short of validation on the file too. File upload is always been a complex work in java web server development but we will see how struts 1 makes it so easy to upload a file. First of all lets see the requirements of our example. These are :

  1. Upload a file and store it to the temp directory of tomcat 6.
  2. The file must be an image of format in jpeg or jpg or pjpeg. No other formats are allowed.
  3. The file size must be <= 50000 bytes.

So, how will we implement it. Here are the steps followed to implement the example code :

  1. At the first step, we will create a form bean ( that will hold the uploaded file and its name. The validate method of form bean will validate the file as per requirements 2 and 3 listed above.
  2. Then, we will implement action class ( that will perform the required action in the example. If the file is according to the requirement, then it will store the file to the temp directory of tomcat 6 server and if not it will show back the upload html form.
  3. After that we will create two jsp files. One for showing the upload form (FileUpload.jsp) to the user where user will select a file and will try to upload the selected file and the other (success.jsp) will show only if file is saved to the server successfully.

UploadForm class contains instance of org.apache.struts.upload.FormFile class provided by the struts that automatically handles file data sent by the browser. The upload form also contains property as “fileName” which will store the name of the file. The bellow is the code for :

package com.raistudies.forms;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;

public class UploadForm extends ActionForm {

    private static final long serialVersionUID = 2025885369419610335L;

    private FormFile uploadedFile = null;
    private String fileName = null;

    //    Getters, setters  and reset methods are omitted for making the code short.

    public ActionErrors validate(ActionMapping mapping,
    HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if(uploadedFile.getFileSize() == 0)
             errors.add("uploadedFile", new ActionMessage("errors.file.notselected"));
            if(!uploadedFile.getContentType().equalsIgnoreCase("image/jpeg") && !uploadedFile.getContentType().equalsIgnoreCase("image/jpg")
            && !uploadedFile.getContentType().equalsIgnoreCase("image/pjpeg"))
                errors.add("uploadedFile", new ActionMessage("errors.file.type", uploadedFile.getFileName(),uploadedFile.getContentType()));
            if(uploadedFile.getFileSize() > 50000)
                errors.add("uploadedFile", new ActionMessage("errors.file.size",uploadedFile.getFileName(),uploadedFile.getFileSize()));
        return errors;

The validations are also implemented in in validate method. Let us see that is going on the validate method :

  • uploadedFile.getContentType() : -returns the format of the file. So, this method is used to check if the file is not of format “image/jpeg”, “image/jpg” or “image/pjpeg”.
  • uploadedFile.getFileSize() : – returns the size of the file uploaded. If the size is zero that means file has not been selected. This method is also used to check that if the size of the file is greater that 50000 bites, the error will be added.

Following is code in execute method of UploadAction class :

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
    UploadForm uploadForm = (UploadForm)form;
    FileOutputStream outputStream = null;
    String filePath = System.getProperty("") + "/" + uploadForm.getUploadedFile().getFileName();
    try {
        outputStream = new FileOutputStream(new File(filePath));
    } catch (Exception e) {
        ActionErrors errors = new ActionErrors();
        errors.add("uploadedFile",new ActionMessage("",uploadForm.getUploadedFile().getFileName()));
        if(outputStream != null)
    if(getErrors(request) == null ||getErrors(request).size() == 0){
        return mapping.findForward("success");
        return mapping.getInputForward();

The execute method do the process for saving the file in the temp directory of tomcat 6. To get the path of temp directory of tomcat 6, I get the value of system property “”, whose value is the path of temp directory on tomcat 6 while run the application in tomcat server. After that we store the file using FileOutputStrean class. If some error occur during the save process, we will show the error to user.


FileUpload.jsp is not very much different with other jsp files of struts. Only one variation is the use of <html:file> for selecting a file at user side and sent to the server for processing.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Upload File in this page</title>
        <html:form action="/fileUpload" enctype="multipart/form-data" method="POST">
            Select File : <html:file property="uploadedFile"/><br/>
            <html:submit value="Upload"/>


In struts-config.xml, we have configured our action class, form bean and views.  Here is the configuration detail :

    <!-- ========== Form Bean Definitions ================================== -->
        <form-bean name="uploadForm" type="com.raistudies.forms.UploadForm"/>
    <!-- ========== Action Mapping Definitions ============================= -->
        <action name="uploadForm" path="/fileUpload" input="/FileUpload.jsp"
        type="com.raistudies.actions.UploadAction" scope="session" validate="true">
            <forward name="success" path="/success.jsp"/>
    <message-resources parameter="ApplicationResources"/>

If file is been saved successfully, success.jsp will be shown to the user for confirmation.

While deploy the war file of the example to Tomcat 6 and hit the url in browser you will initially get the following page :

File Upload Form

File Upload Form

Just do not select any file and click on “Upload” button, the following error screen will come to show :

No File Selected Upload Error

No File Selected Upload Error

Then, try bu selecting any file that is not image and whose size is also getter than 50000 bites, you will see following error page :

File Upload Size Error

File Upload Size Error

Then, if you select a correct file, it would be uploaded and stored in temp directory of tomcat server.

You can download code and war file of the example from the following links :

Code : Download

War : Download

Related Posts:

Leave a Comment Cancel reply

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>