File upload in Struts 1.2 with Example code.

The following tutorial explains the techniques to upload files to a server using Struts 1.2. The earlier version of  Servlet (I.e. prior to servlet 3.0) , requires external libraries to implement  file upload.  Struts makes things much easier to upload files. Steps involved to upload a file using struts framework 1.2 or 1.3.

Step 1. Design web form for uploading a file . Use the html:file tag which enables the user to browse and select a file from the local machine and set the encoding type of html:form tag to “multipart/form-data” and specify the HTTP method as “post”. The part of the code of the JSP is as follows


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<script language="javaScript">
   function submitForm(){
      document.uploadForm.method.value = "fileUploadAction";
   <html:errors />
<html:form name="uploadForm" type="com.javaonline.struts.FileUploadForm" method="post" action="/" enctype="multipart/form-data">
 <html:hidden property="method" value="fileUploadAction" />
 <tr><td>File Name: </td>
 <td ><html:file name="uploadForm" property="dataFile" /></td>
 <tr><td align="center"><a href="javascript:submitForm()" name="continue_button"> Submit </a></td>


In the above code , FileUploadForm is the Form bean which extends ActionForm . enctype attribute is set to “multipart/form-data”

Step 2. Create an ActionForm bean for creating form properties and writing validation method

package com.javaonline.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class FileUploadForm extends ActionForm {
	   private FormFile dataFile = null;
	   public ActionErrors validateFileUpload(ActionMapping mapping, HttpServletRequest request) {
		    ActionErrors errors = new ActionErrors();
		    FormFile dataFile = this.getDataFile();
		    String dataFileName = dataFile.getFileName();
		    if (dataFile == null) {
		       errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("invalid.file"));
		    }else if (dataFileName == null || dataFileName.length() == 0) {
		       errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("file.required"));
		    } else if (!dataFileName.matches("[a-zA-Z0-9\\s\\-]+\\.pdf")) {
		       errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("filename.invalid"));
		      } else if (dataFile.getFileSize()>2097152) { //2mb
		   errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("file.size.invalid"));

	    return errors;

	 public FormFile getDataFile() {return dataFile; }
	 public void setDataFile(FormFile file) {dataFile = file; }

In the above code, only one form property dataFile is declared in the type FormFile . FormFile class represents a file that has been uploaded by a client. It has many methods. Some of the useful methods are ,

1. getFileData() returns the data for the entire file as byte array.

2. getInputStream() returns an input stream for this file.

3. getContentType() returns the content type for this file.

4. getFileName() returns the file name of this file.

You have to write a method (here validateFileUpload()) in ActionForm which will have the conditions to validate the file. I have written some of the conditions to validate the file which are as follows .

Should not be blank

File name can not have special characters except – , it allows space. The extension should be pdf.

File size should not be greater than 2 mb.

This condition can be changed as per your requirement.

You can also have following condition to check the content type

if (!dataFile.getContentType().equalsIgnoreCase("application/pdf")) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("invalid.file")); }[/code]

Step 3. Write Action class to to read the file and write to the any given location in the server

package com.javaonline.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

public class FileUploadAction extends DispatchAction {
	   public ActionForward fileUploadAction( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	  throws Exception {
	      ActionErrors errors = new ActionErrors();
	      ActionForward forward = new ActionForward();
	      FileUploadForm uploadForm = (FileUploadForm) form;
	      String target = "";
	      errors = uploadForm.validateFileUpload(mapping, request);   // to validate the given file
	      if (!errors.isEmpty())
	    	  		saveErrors(request, errors);
			          target = "uploadform";
	        } else {

			      try {
			        FormFile dataFile = uploadForm.getDataFile();
			        String fileName = dataFile.getFileName();
			        int  fileSize = dataFile.getFileSize();
			        byte[] fileData = dataFile.getFileData();
			        FileOutputStream fileOut = new FileOutputStream("c:\\temp\\" + fileName);
			        fileOut.write(fileData, 0, fileSize);
			         } catch (Exception e) {
			        	 System.out.println("Error ="+e.toString());
			                    errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.upload", e.toString()));
			                    target = "uploadform";
			        if (!errors.isEmpty()) {
			              saveErrors(request, errors);
			              target = "uploadform";
			          } else { target = "success";    }
	        forward = mapping.findForward(target);
	        return (forward);

The above code is used to read the contents of the file into an byte array, then the byte array is written to the given file name in the given directory of the server. In our example getFileData() is used to read the contents . You can use getInputStream() method for larger file upload.

Step 4. Associate a FormBean with an action in the struts-config.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"


	<!-- Form Beans -->
		<form-bean name="uploadForm" type="com.javaonline.struts.FileUploadForm"/>

	<!-- Action Mappings -->
		<action name="uploadForm" path="/fileUpload" type="com.javaonline.struts.FileUploadAction" parameter="method">
 		<forward name="uploadform" path="/fileUpload.jsp"></forward>
 		<forward name="success" path="/fileUploadSuccess.jsp"></forward>


	<!-- Message Resources -->
	<message-resources parameter="props.ApplicationResources"/>


Step 5: Create a JSP file (fileUploadSuccess.jsp) for displaying  successful upload message.

Step 6.The contents of the are as follows

invalid.file=Invalid File

file.required=Select a file

filename.invalid=File Name invalid

file.size.invalid=file size invalid

Opening the fileUpload.jsp will display the following output


Select the file to upload.


The above selected file size is above 2mb. So the following  error  file size invalid is displayed


Reference : struts upload

You may also like

Leave a Reply