May [Revision number: V5.5.1-1] |
|
|
This tutorial describes how to use NetBeans Visual Web Pack 5.5 to upload and display an image (JPEG, PJPEG, GIF, PNG, or X-PNG) file. Also included is a mini-tutorial on how to upload a text file. |
This tutorial works with the following technologies and resources
JavaServer Faces Components/
Java EE Platform |
1.2 with Java EE 5*
1.1 with J2EE 1.4
|
Travel Database |
Not required |
BluePrints Ajax Component Library |
Not required |
* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.
This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17.
If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds.
For detailed information about the
supported servers and Java EE platform, see the Release Notes.
About the File Upload Component
The File Upload component enables users of your web application to locate a file on their system and upload that file to the server. This component is useful for collecting text files, image files, and other data. The contents of the uploaded file are stored together with some information about the file, including the file name, size, and MIME type (such as text/plain or image/jpeg).
The server holds the uploaded file in memory unless it exceeds 4096 bytes, in which case the server holds the file contents in a temporary file. You can change this threshold by modifying the sizeThreshold parameter for the UploadFilter filter entry in the web application's web.xml file. For more information on modifying the web.xml file, see the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.
In cases where you want to retain the uploaded file, you have three choices:
- Write the file to a location of your choice, as shown in this tutorial.
- Create an
UploadedFile property in a managed bean and set it to the component's value before you exit the page (as in the button's action method).
- Save the file to a database.
By default, the File Upload component can handle files up to one megabyte in size. You can change the maximum file size by modifying the maxSize parameter for the UploadFilter filter entry in the application's web.xml file, as described in the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.
Creating a Page That Includes a File Upload Component
First, you build a form that enables users to select a file to upload.
-
Create a new Visual Web Application project and name it FileUploadExample .
Figure 1 shows the page that you will create in the steps that follow:
Figure 1: File Upload Page Design |
- From the Basic section of the Palette, drop a Label component on the page, type
Choose a File to Upload: and press Enter.
- Drag a File Upload component onto the page and drop it underneath the Label component.
- Drag a Button component onto the page, type
Upload File , and press Enter. In the Properties window, set the Button's id property to
uploadFileButton .
- Drag a Label component onto the page and set the text to
File Name:
- Place a Static Text component to the right of the Label. In the Properties window, set the Static Text's
id property to fileNameStaticText .
- Drag another Label onto the page. Set the text of the Label to
File Type:
- Place a Static Text component to the right of the new Label. Set the
id of the Static Text to fileTypeStaticText .
- Drag another Label and Static Text pair onto the page. Set the text of the Label to
File Size: and the id of the Static Text to fileSizeStaticText .
- Place an Image component below the Static Text components.
- Place a Message Group component below the Image component.
Adding Code to Handle Image Uploads
Now that you have the basic file upload form, you must add code to handle the file upload.
Double-click the Upload File button to open the Java Editor and add the button's event handler, uploadFileButton_action, to the page bean.
Before adding code to this method, you define variables for storing the image file and add code to the init() and prerender() methods.
Scroll up to the init() method and add the following two variables before the method.
Code Sample 1: Variables |
private String realImageFilePath;
private static final String IMAGE_URL = "/resources/image-file"; |
The variable realImageFilePath is the actual path and filename of the image file on the server. The IMAGE_URL variable is the logical path of the image file in the running web application.
-
Add the following lines of bold (shown in bold) at the end of the init method, but note that the code contains a Class Not Found error. You add import statements to fix these errors in step 6. After inserting the code, you can press Ctrl-Shift-F to reformat the code.
Code Sample 2: init Method |
public void init() {
super.init();
// Perform application initialization that must complete
// *before* managed components are initialized
// TODO - add your own initialiation code here
// Managed Component Initialization
// Perform application initialization that must complete
// *after* managed components are initialized
// TODO - add your own initialization code here
ServletContext theApplicationsServletContext =
(ServletContext) this.getExternalContext().getContext();
this.realImageFilePath = theApplicationsServletContext.getRealPath(IMAGE_URL);
}
|
This code converts IMAGE_URL into the real image file path so that the file can be written to the correct directory on the server.
-
Scroll to the prerender method and add the following code:
Code Sample 3: prerender Method |
public void prerender() {
String uploadedFileName = (String)
this.fileNameStaticText.getValue();
if ( uploadedFileName != null ) {
image1.setUrl(IMAGE_URL);
}
}
|
If there is an image file to display, this code
binds the file to the Image component.
Add the following code to the uploadFileButton_action() method
Code Sample 4: Code to Upload an Image File |
public String uploadFileButton_action() {
UploadedFile uploadedFile = fileUpload1.getUploadedFile();
String uploadedFileName = uploadedFile.getOriginalName();
// Some browsers return complete path name, some don't
// Make sure we only have the file name
// First, try forward slash
int index = uploadedFileName.lastIndexOf('/');
String justFileName;
if ( index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// Try backslash
index = uploadedFileName.lastIndexOf('\\');
if (index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// No forward or back slashes
justFileName = uploadedFileName;
}
}
this.fileNameStaticText.setValue(justFileName);
Long uploadedFileSize = new Long(uploadedFile.getSize());
this.fileSizeStaticText.setValue(uploadedFileSize);
String uploadedFileType = uploadedFile.getContentType();
this.fileTypeStaticText.setValue(uploadedFileType);
if ( uploadedFileType.equals("image/jpeg")
|| uploadedFileType.equals("image/pjpeg")
|| uploadedFileType.equals("image/gif")
|| uploadedFileType.equals("image/png")
|| uploadedFileType.equals("image/x-png")) {
try {
File file = new File(this.realImageFilePath);
uploadedFile.write(file);
} catch (Exception ex) {
error("Cannot upload file: " + justFileName);
}
} else {
error("You must upload a JPEG, PJPEG, GIF, PNG, or X-PNG file.");
new File(this.realImageFilePath).delete();
}
return null;
} |
For each file, the program extracts the file name, size, and type from the UploadedFile object and binds
them to the Static Text components. The program makes a key decision with all uploads: If the file is a JPEG,
PJPEG, GIF, PNG, or X-PNG file, the program saves the uploaded file to the realImageFilePath variable. If the file is not a valid image file or if there are other problems uploading the file, the program deletes the image from the server and displays an error message.
Right-click in the Java Editor and choose Fix Imports. In the Fix Import dialog box, ensure that java.io.File appears in the Fully Qualified Name field and click OK.
This action fixes the errors in the code.
Testing the Application
- Run the application.
-
Click Browse to navigate through your local drives and select a file to upload. Then click the Upload File button.
The following figure shows the application with an uploaded JPEG file. The image is stored in project-directory\FileUploadExample\build\web\resources .
Figure 2: Application With Uploaded Image |
-
Enter a text file in the File Upload component and click the Upload File button. Verify that the error message displays.
Note: The rendering of the File Upload
component can differ depending on the web browser. Be sure to test this
component in the web browsers that you expect your users to use.
Doing More #1: Uploading a Text File
This section is a mini-tutorial on how to upload a text file. This example displays the file contents in a text area component, and the file name and size in a message group component. This example does not save the contents of the file. To do so, you must add code to save the file to disk, as shown in the previous example.
- Create a new Visual Web Application project.
- Drag a File Upload component onto the page.
- Add a Button component, a Text Area component, and a Message Group component.
-
Double-click the Button component and add the following action code to the button1_action() method:
Code Sample 5: Code to Upload a Text File |
public String button1_action() {
UploadedFile uploadedFile = (UploadedFile)
fileUpload1.getUploadedFile();
info("Uploaded file originally named '" +
uploadedFile.getOriginalName() +
"' of size '" + uploadedFile.getSize() + "'");
textArea1.setText(uploadedFile.getAsString());
return null;
} |
- Press Alt-Shift-F to fix imports and automatically add the
UploadedFile import statement.
-
Run the application. The following figure shows a sample page.
Figure 3: Text File Upload |
Doing More #2: Modifying the Maximum File Upload Size
To enable the upload of a file greater than one megabyte (such as a large image file, ZIP, JAR, or executable file), you must modify the maxSize parameter for the UploadFilter filter in your application's web.xml file.
- Open the Files window and expand project-name > web > WEB-INF.
- Right-click the web-xml node and choose Edit.
- In the XML editor, click the Filters button.
- Select the
maxSize parameter for the UploadFilter , and click the Edit button.
-
In the dialog box, set Param Value to the desired value and click OK.
Note: For security reasons, do not set the maxSize parameter to a negative value, which indicates that there is no file size limit.
- Choose File > Save to save your changes.
Note: If a user of your application tries to upload a file larger than the value of the maxSize parameter,
the following exception is thrown and caught as a validation error:
org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException
The summary message displayed to users reads:
No file was uploaded
The detail message reads:
No file was uploaded. The specified file exceeds the maximum allowable size of 1000000 Mb
where 1000000 Mb is the value of maxSize .
Doing More #3: Saving the Uploaded Files to Other Locations
This tutorial shows how to upload a file to the web application's /resources folder.
What if you want to save the uploaded files elsewhere? Here are some alternatives.
A Different Folder in the Web Application
You can put the images in any directory in the web application
(that is, any directory under the web application's web directory).
For example, you can create an upload/images subfolder under web and use the following code to store the images there:
Code Sample 6: Code to Upload a File to a Different Folder |
String realPath = theApplicationsServletContext.getRealPath("/upload/images");
File file = new File(realPath + File.separatorChar + justFileName);
|
Be careful when putting the uploaded files in the web application because anyone can
access the files by URL.
A Known Directory on the Server
To store the images somewhere else on the server, you can use code such as the following:
Code Sample 7: Code to Upload a File to a Known Directory on a Server |
File file = new File("C:/upload/images" + File.separatorChar + justFileName);
uploadedFile.write(file);
|
If you plan to deploy the application to different servers, you might use code like the following to ensure that the upload directory exists:
Code Sample 8: Code to Upload a File to Different Servers |
File dir = new File("C:/upload/images");
if (! dir.exists()) dir.mkdirs();
File file = new File(dir.getCanonicalPath() + File.separatorChar + justFileName);
uploadedFile.write(file);
|
For more information about the File class.
An As-Yet Unknown Directory
Another alternative is to put the directory path in the deployment descriptor so that you can change the location dynamically.
- In the Files window, expand the web node and then expand WEB-INF. Double-click web.xml to open it.
- Click the General button and expand Context Parameters, and click the Add button.
-
Set the following values, and then click OK.
Param Name: uploadDirectory (or whatever you want to name it)
Param Value: C:/upload/images (or whatever your path is)
- Close and save the
web.xml file.
-
Use the following code:
Code Sample 9: Code to Upload a File to an As-Yet Unknown Directory |
String uploadDirectory = getExternalContext().getInitParameter
("uploadDirectory");
File file = new File(uploadDirectory + File.separatorChar + justFileName);
uploadedFile.write(file);
|
Known Issues
- If you run the File Upload tutorial using Internet Explorer 7, the first load of the image works properly.
The second load of the image updates the file name, file type, and file size, but does not update the image. If you reload the browser, the image
displays correctly.
- The filename of the image must contain ISO-8859-1 characters.
See Also:
This page was last modified: May 24,
|