DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Struts File Upload Tutorial

Meyyappan Muthuraman user avatar by
Meyyappan Muthuraman
·
Jun. 15, 12 · Tutorial
Like (0)
Save
Tweet
Share
69.25K Views

Join the DZone community and get the full member experience.

Join For Free
In this tutorial we will see how to allow the user to upload a file using Struts. In order to allow the user to upload a file, we need to set the encoding type of html:form tag to "multipart/form-data" and specify the HTTP method as "post". The html:file tag enables the user to browse and select a file.
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
    File : <html:file property="file" /> <br/>
    <html:submit />
</html:form>

The property file in the FileUploadForm is of type FormFile (org.apache.struts.upload.FormFile). We will check whether the file uploaded by the user satisfies the following conditions in the FileUploadForm's validate() method.

  • Should be an Excel File.
  • File size should not exceed 20kb.

The validate() method of the FileUploadForm contains the following code.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    if (file.getFileSize() == 0) {
    	errors.add("file", new ActionMessage("error.file.required"));
    } else if (!file.getContentType().equals("application/vnd.ms-excel")) {
    	errors.add("file", new ActionMessage("error.file.type"));
    }
    /**
    * If the file size is greater than 20kb.
    */
    else if (file.getFileSize() > 20480) {
    	errors.add("file", new ActionMessage("error.file.size"));
    }
    return errors;
}

The getFileSize() method returns the size of the file. The getContentType() method returns the content type of the file selected by the user.

We save the file uploaded by the user in the server. To do this we first get the file uploaded by the user using the getFile() method. The getFile() mehtod returns a FormFile object. Using the FormFile object we can get details regarding the file like file name and file data.

The FileUploadAction contains the following code.

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  FileUploadForm uploadForm = (FileUploadForm) form;
  FileOutputStream outputStream = null;
  FormFile formFile = null;
  try {
      formFile = uploadForm.getFile();
      String path = getServlet().getServletContext().getRealPath("")+"/"+
      formFile.getFileName();
      outputStream = new FileOutputStream(new File(path));
      outputStream.write(formFile.getFileData());
  } 
  finally {
      if (outputStream != null) {
          outputStream.close();
      }
  }
uploadForm.setMessage("The file "+formFile.getFileName()+" is uploaded successfully.");
return mapping.findForward(SUCCESS);
}

The getFileData() method returns the entire file as a byte[]. This method should be used only when the file size is small, incase of large files its better to use getInputStream() method.

On executing the example the following page will be displayed to the user.

When the user submits the form without selecting any file the following message is dispalyed to the user.


When the user selects a file other than an Excel file then the following message is dispalyed to the user.


When the user selects a file that is greater than 20kb then the following message is dispalyed to the user.


When the user selects an excel file that is less than 20kb, then the user is forwarded to the success page.



  • Download the example and copy it inside the webapps directory of the Tomcat sever.
  • Run the example using the following url "http://localhost:8080/Example23/".
  • Select an excel file to upload.
  • The excel file will be saved inside the Example directory in the server.
  • For example, when I uploaded the temp.xls file the file got stored in the following location "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\Example23\temp.xls".


You can download the source code of the File Upload example by clicking on the Download link below.

Source :Download
Source + Lib :Download
Upload

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • Reconciling Java and DevOps with JeKa
  • Key Elements of Site Reliability Engineering (SRE)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: