0% found this document useful (0 votes)
0 views10 pages

Chapter - 005 Struts File Upload

This chapter explains how to implement file uploads in Struts using the File Upload interceptor and the Jakarta Commons FileUpload library. It covers the setup for both single and multiple file uploads, including form structure, action classes, and error handling. Two examples demonstrate the process of uploading files, showcasing the necessary configurations and code implementations.

Uploaded by

shakir.hello
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views10 pages

Chapter - 005 Struts File Upload

This chapter explains how to implement file uploads in Struts using the File Upload interceptor and the Jakarta Commons FileUpload library. It covers the setup for both single and multiple file uploads, including form structure, action classes, and error handling. Two examples demonstrate the process of uploading files, showcasing the necessary configurations and code implementations.

Uploaded by

shakir.hello
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 12.

File Upload
HTTP file upload is specified in Request For Comments (RFC) 1867. Struts' File Upload
interceptor supports HTTP file upload by seamlessly incorporating the Jakarta Commons
FileUpload library that contains a multipart parser. This chapter discusses file upload in
general and how you can do single and multiple file uploads in Struts.

File Upload Overview


When using an HTML form to upload a file or multiple files, the enctype attribute of the
form must be assigned multipart/form-data and the form method must be post. The
form should look like this.

<form action="anAction" enctype="multipart/form-data" method="post">


...
</form>

To enable the user to select a file you must have an <input type="file"> field. Here is an
example of a form used for selecting a file. In addition to a file field, the form also contains
a text box named description and a submit button.

<form action="[Link]" enctype="multipart/form-data"


method="post">
Select file to upload <input type="file" name="filename"/><br/>
Description: <input type="text" name="description"/><br/>
<input type="submit" value="Upload"/>
</form>

Figure 12.1 shows how the file input field is rendered as a text box and a Browse
button.

Figure 12.1. Rendered visual elements of <input type=file>

Without Struts or the Java Commons FileUpload library, you would have to call the
getInputStream method on HttpServletRequest and parse the resulting InputStream
object to retrieve the uploaded file. This is a tedious and error-prone task. Luckily, Struts
makes it very easy to retrieve uploaded files.
File Upload in Struts

In Struts, the File Upload interceptor and the Jakarta Commons FileUpload library help parse
uploaded files. Basically, there are only two things you need to do.

First, use the file tag in a form on your JSP. Give it a descriptive name such as attachment
or upload. For multiple file upload, use multiple file tags and give them the same name. For
instance, the following form contains three file tags named attachment.

<s:form action="File_multipleUpload"
enctype="multipart/form-data">
<s:file name="attachment" label="Attachment 1"/>
<s:file name="attachment" label="Attachment 2"/>
<s:file name="attachment" label="Attachment 3"/>
<s:submit />
</s:form>

A file tag will be rendered as the following input element in the browser:

<input type="file" name="inputName"/>

Second, create an action class with three properties. The properties must be named
according to these patterns:

• [inputName] File
• [inputName]FileName
• [inputName]ContentType

Here [inputName] is the name of the file tag(s) on the JSP. For example, if the file tag's
name is attachment, you will have these properties in your action class:

• attachmentFile
• attachmentFileName
• attachmentContentType

For single file upload, the type of [inputName] File is [Link] and references the
uploaded file. The second and third properties are String and refer to the uploaded file name
and the content type, respectively.

For multiple file upload, you can either use arrays or [Link]. For instance, the
following properties are arrays of Files and Strings.

private File[] attachmentFile;


private String[] attachmentFileName;
private String[] attachmentContentType;

If you decide to use Lists, you must assign an empty list to each of the properties:
private List<File> attachmentFile = new ArrayList<File>();
private List<String> attachmentFileName = new ArrayList<String>();
private List<String> attachmentContentType =
new ArrayList<String>();

You can access these properties from your action method. Normally, you would want to
save the uploaded file into a folder or a database and you would iterate over the File array,
if an array is being used:

ServletContext servletContext =
[Link]();
String dataDir = [Link]("/WEB-INF");
for (int i=0; i < [Link]; i++) {
File savedFile = new File(dataDir, attachmentFileName[i]);
attachment[i].renameTo(savedFile);
}

Since you often need to access both the uploaded file and the file name at each iteration,
using arrays is easier because an array lets you iterate over its elements by index. On the
other hand, iterating over a list would be more difficult.

The File Upload Interceptor

This interceptor is responsible for file upload and is included in the default stack. Even if you
know nothing about this interceptor, you can still manage uploaded files easily. However,
understanding how this interceptor works allows you to make full use of the file upload
feature in Struts.

There are two important properties that you may want to set on the interceptor. You can
limit the size of the uploaded file as well as determine the allowable content type by setting
the following properties of the File Upload interceptor.

• maximumSize. The maximum size (in bytes) of the uploaded file. The default is
about 2MB.
• allowedTypes. A comma-separated list of allowable content types.

For example, the following action imposes a size limit and the type of the uploaded file. Only
files up to 1,000,000 bytes in size and JPEG, GIF, and PNG files can be uploaded.

<action name="File_upload" class="[Link]">


<interceptor-ref name="fileUpload"/>
<param name="maximumSize">1000000</param>
<param name="allowedTypes">
image/gif,image/jpeg,image/png
</param>
</interceptor-ref>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
...
</action>
If the user uploaded a file that is larger than the specified maximum size or a type not in
the allowedTypes parameter, an error message will be displayed. File upload-related error
messages are predefined in the [Link] file which is included in the core
Struts JAR file. Here are the contents of the file:

[Link]=Error uploading: {0}


[Link]=File too large: {0} "{1}" {2}
[Link]=Content-Type not
allowed: {0} "{1}" {2}

To override the messages here, create a [Link] file that contains


values that you want to override the default values and place the file under WEB-
INF/classes/org/apache/struts2. If you create a new [Link] file, the
default one will not be examined. This means, if you override one message key and decide
to use the other default ones, you must copy the latter to your properties file.

Single File Upload Example


The app12a application is a Struts application for uploading a file. The directory structure is
shown in Figure 12.2.

Figure 12.2. app12a directory structure

There are two actions in this application, one for displaying a file upload form and one for
receiving the uploaded file. The action declarations are printed in Listing 12.1.
Listing 12.1. The [Link] file
<package name="app12a" extends="struts-default">
<action name="File">
<result>/jsp/[Link]</result>
</action>

<action name="File_singleUpload"
class="[Link]" method="upload">
<interceptor-ref name="fileUpload">
<param name="maximumSize">100000</param>
<param name="allowedTypes">
image/gif,image/jpeg,image/png
</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="input">/jsp/[Link]</result>
<result>/jsp/[Link]</result>
</action>
</package>

The [Link] page (shown in Listing 12.2) contains a form with a file tag.

Listing 12.2. The [Link] page


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload</title>
<style type="text/css">@import url(css/[Link]);</style>
</head>
<body>
<div id="global">
<h1>Single File Upload</h1>
<s:fielderror />
<s:form action="File_singleUpload"
enctype="multipart/form-data">
<s:textfield name="description" label="Description"/>
<s:file name="attachment" label="Attachment"/>
<s:submit />
</s:form>
</div>
</body>
</html>

When the user submits the form, the File_singleUpload action will be invoked. The
SingleFileUploadAction class in Listing 12.3 handles this action.
Listing 12.3. The SingleFileUploadAction class
package app12a;
import [Link];
import [Link];
import [Link];
import [Link];

public class SingleFileUploadAction extends ActionSupport {


private File attachment;
private String attachmentFileName;
private String attachmentContentType;
private String description;

// getters and setters not shown

public String upload() throws Exception {


[Link](description);
ServletContext servletContext =
[Link]();
if (attachment != null) {
// attachment will be null if there's an error,
// such as if the uploaded file is too large
String dataDir = [Link]("/WEB-INF");
File savedFile = new File(dataDir, attachmentFileName);
[Link](savedFile);
}
return SUCCESS;
}
}

The action class has three properties, attachmentFileName, attachmentContentType,


and description, the first two of which are related to the uploaded file. It saves the
uploaded file under WEB-INF, but you can choose a different location.

The app12a application also overrides the custom error messages by providing a new
[Link] file in Listing 12.4.

Listing 12.4. The [Link] file


[Link]=Error. File type not
allowed.
[Link]=Error. File too large.

Run the app12a application by invoking this URL.

[Link]

You'll see the upload form like the one in Figure 12.3.
Figure 12.3. Single file upload

Multiple File Upload Example


The app12b application demonstrates multiple file upload. There are two actions in
app12b, File (for displaying a file upload form) and File_multipleUpload (for handling the
uploaded files). The action declarations are shown in Listing 12.5.

Listing 12.5. The action declarations


<package name="app12b" extends="struts-default">
<action name="File">
<result>/jsp/[Link]</result>
</action>
<action name="File_multipleUpload"
class="[Link]" method="upload">
<result name="input">/jsp/[Link]</result>
<result>/jsp/[Link]</result>
</action>
</package>

The File action displays the [Link] page in Listing 12.6.


Listing 12.6. The [Link] page
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload</title>
<style type="text/css">@import url(css/[Link]);</style>
</head>
<body>
<div id="global">
<h1>Multiple File Upload</h1>
<s:actionerror />
<s:fielderror />
<s:form action="File_multipleUpload"
enctype="multipart/form-data">
<s:file name="attachment" label="Attachment 1"/>
<s:file name="attachment" label="Attachment 2"/>
<s:file name="attachment" label="Attachment 3"/>
<s:submit />
</s:form>
</div>
</body>
</html>

When the file upload form is submitted, the File_multipleUpload action is invoked. This
action is handled by the MultipleFileUploadAction class in Listing 12.7. Note that
arrays are used for the uploaded files, file names, and content types.

Listing 12.7. The MultipleFileUploadAction class


package app12b;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MultipleFileUploadAction extends ActionSupport {


private File[] attachment;
private String[] attachmentFileName;
private String[] attachmentContentType;

// getters and setters not shown


public String upload() throws Exception {
ServletContext servletContext =
[Link]();
String dataDir = [Link]("/WEB-INF");
for (int i=0; i < [Link]; i++) {
File savedFile = new File(dataDir,
attachmentFileName[i]);
attachment[i].renameTo(savedFile);
}
return SUCCESS;
}
}

You can start uploading multiple files by directing your browser here.

[Link]

You'll see a form similar to the one in Figure 12.4.

Figure 12.4. Multiple file upload

You can also use Lists instead of arrays. The MultipleFileUploadAction2 class in Listing
12.8 shows how to use Lists. Note that you must instantiate a List implementation for the
List variables.
Listing 12.8. Using Lists
package app12a;
import [Link];
import [Link];
import [Link];
import [Link];
public class MultipleFileUploadAction2 extends ActionSupport {
private List<File> attachment =
new ArrayList<File>();
private List<String> attachmentFileName =
new ArrayList<String>();
private List<String> attachmentContentType =
new ArrayList<String>();

// getters and setters not shown

public String upload() throws Exception {


for (String fileName : attachmentFileName) {
[Link](fileName);
}
return SUCCESS;
}
}

Using arrays are better than Lists because with arrays you can iterate over the uploaded
files over by index.

Summary
This chapter discussed file upload. Struts supports file upload through the File Upload
interceptor that incorporates the Jakarta Commons FileUpload library. Two examples that
illustrated single file upload and multiple file upload were presented in this chapter

You might also like