Struts File Upload

Here we will learn about how to upload a file using the struts framework. Struts file upload examples are also explained here. Multiple struts file upload are also explained here.The brain of the strut file upload application is the interface org. apache.struts.upload.FormFile. It is a file that has been uploading by a client.

Steps for uploading file: –

1)  Creating form bean

Form bean class includes the property called the File and its type is org.apache.struts.upload.FormFile.

Code of FormBean or StructUploadForm.java: –

package mysite.com;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
/**
* Form bean for Struts File Upload.
*
*/
public class StrutsUploadForm extends ActionForm
{
private FormFile theFile;

/**
* @return Returns the theFile.
*/
public FormFile getTheFile() {
return theFile;
}
/**
* @param theFile The FormFile to set.
*/
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
} }

2)  Creating action class: –

Action class calls the getTheFile() function in the FormBean object to retrieve the reference of the upload file.

Code for action class(StrutsUpoladAction.java): –

 
package mysite.com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
/**
* Struts File Upload Action Form.
**/
public class StrutsUploadAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
StrutsUploadForm myForm = (StrutsUploadForm)form;
// Process the FormFile
FormFile myFile = myForm.getTheFile();
String contentType = myFile.getContentType();
String fileName  = myFile.getFileName();
int fileSize = myFile.getFileSize();
byte[] fileData  = myFile.getFileData();
System.out.println(“contentType: “ + contentType);
System.out.println(“File Name: “ + fileName);
System.out.println(“File Size: “ + fileSize);
return mapping.findForward(“success”);
}
}

3)  Defining form Bean in struts-config.xml file: –

The strut-config.xml file helps to defining the form bean.

Syntax: –

 <form-bean
name=“FileUpload”
type=“mysite.com.StrutsUploadForm”/>

4)  Defining action mapping: –

The following code into the strut-config.xml file helps to specify the action mapping.

Syntax: –

action
path=“/FileUpload”
type=“mysite.com.StrutsUploadAction”
name=“FileUpload”
scope=“request”
validate=“true”
input=“/pages/FileUpload.jsp”>
<forward name=“success” path=“/pages/uploadsuccess.jsp”/>
</action>

5)  Developing jsp page: –

Code for developing jsp page is as follows. FileUpload.jsp

<%@ taglib uri=“/tags/struts-bean” prefix=“bean” %>
<%@ taglib uri=“/tags/struts-html” prefix=“html” %>
<html:html locale=“true”>
<head>
<title>Struts File Upload Example</title>
<html:base/>
</head>
<body bgcolor=“white”>
<html:form action=“/FileUpload” method=“post” enctype=“multipart/form-data”>
<table>
<tr>
<td align=“center” colspan=“2”>
<font size=“4”>Please Enter the Following Details</font>
</tr>
<tr>
<td align=“left” colspan=“2”>
<font color=“red”><html:errors/></font>
</tr>
<tr>
<td align=“right”>
File Name
</td>
<td align=“left”>
<html:file property=“theFile”/>
</td>
</tr>
<tr>
<td align=“center” colspan=“2”>
<html:submit>Upload File</html:submit>
</td>
</tr>
</table>
</html:form>
</body>
</html:html>

6)  Define uploadsuccess.jsp page.

Syntax: –

<html>
<head>
<title>Success</title>
</head>
<body>
<p align=“center”><font size=“5” >File Successfully Received</font></p>
</body>
</html>

7)  The below code helps to call the index.jsp page.

Syntax: –

<li>
<html:link page=“/pages/FileUpload.jsp”>Struts File Upload</html:link>
<br></li>

Example shows you how to Upload File with Struts.

Example : –

The below code used to save the file: –

Syntax for StrutsUploadAndSaveAction.java: –

package mysite.com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import java.io.*;
/**
* Struts File Upload Action Form.
*
*/
public class StrutsUploadAndSaveAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
StrutsUploadAndSaveForm myForm = (StrutsUploadAndSaveForm)form;
// Process the FormFile
FormFile myFile = myForm.getTheFile();
String contentType = myFile.getContentType();
//Get the file name
String fileName  = myFile.getFileName();
//int fileSize = myFile.getFileSize();
byte[] fileData  = myFile.getFileData();
//Get the servers upload directory real path name
String filePath = getServlet().getServletContext().getRealPath(“/”) +”upload”;
/* Save file on the server */
if(!fileName.equals(““)){
System.out.println(“Server path:” +filePath);
//Create file
File fileToCreate = new File(filePath, fileName);
//If file does not exists create file
if(!fileToCreate.exists()){
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
//Set file name to the request object
request.setAttribute(“fileName”,fileName);
return mapping.findForward(“success”);
}
}

Uploading multiple files using array: we can upload multiple files using arrays .

Code for multipleUploadUsingArray.jsp: –

<%@ page
language=“java”
contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
<%@ taglib prefix=“s” uri=“/struts-tags” %>
<html>
<head>
<title>Showcase - fileupload - multiple fileupload using List</title>
</head>
<body>
<s:form action=“doMultipleUploadUsingArray”
method=“POST” enctype=“multipart/form-data”>
<s:file label=“File (1)” name=“upload” />
<s:file label=“File (2)” name=“upload” />
<s:file label=“FIle (3)” name=“upload” />
<s:submit />
</s:form>
</body>
</html>

MultipleFileUploadUsingArrayAction.java: –

package mysite.com.struts2.showcase.fileupload;
import java.io.File;
import com.j2eebrain.ActionSupport;
/**
* Showcase action - mutiple file upload using array.
*/
public class MultipleFileUploadUsingArrayAction extends ActionSupport {
private File[] uploads;
private String[] uploadFileNames;
private String[] uploadContentTypes;
public File[] getUpload() { return this.uploads; }
public void setUpload(File[] upload) { this.uploads = upload; }
public String[] getUploadFileName() { return this.uploadFileNames; }
public void setUploadFileName(String[] uploadFileName) { this.uploadFileNames = uploadFileName; }
public String[] getUploadContentType() { return this.uploadContentTypes; }
public void setUploadContentType(String[] uploadContentType) { this.uploadContentTypes = uploadContentType; }
public String upload() throws Exception {
System.out.println(“\n\n upload2”);
System.out.println(“files:”);
for (File u: uploads) {
System.out.println(“*** “+u+”\t”+u.length());
}
System.out.println(“filenames:”);
for (String n: uploadFileNames) {
System.out.println(“*** “+n);
}
System.out.println(“content types:”);
for (String c: uploadContentTypes) {
System.out.println(“*** “+c);
}
System.out.println(“\n\n”);
return SUCCESS;
}
}