corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

Using the File Upload Component

December 2006  [Revision number: V1-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. The tutorial requires a folder with write permissions, because that is where the files will be saved when they arrive at the server. Also included is a mini-tutorial on how to upload a text file.

Contents

About the File Upload Component
Creating a Page That Includes a File Upload Component
Creating a Folder to Receive the Files
Adding Code to Handle Image Uploads
Testing the Application
Doing More #1: Uploading a Text File
Doing More #2: Modifying the Maximum File Upload Size
Doing More #3: Saving the Uploaded File to Other Locations
  Content on this page applies to NetBeans 5.5 Visual Web Pack

This tutorial works with the following resources

NetBeans Visual Web Pack 5.5 works with all supported servers and works with both the Java EE 1.4 and Java EE 5 platforms. This tutorial illustrates the Visual Web Pack features that work with the resources check marked in the following table. For detailed information about the supported servers and Java EE platform, see NetBeans Visual Web Pack 5.5 Installation Instructions.

Application Server works withSun Java System Application Server 9
works withTomcat
works withJBoss
works withBEA WebLogic
JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database requiredNot Required
BluePrints AJAX Component Library not requiredNot Required

* Only the Sun Java System Application Server supports Java EE 5

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.
  1. 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
    Figure 1: File Upload Page Design
  2. From the Basic section of the Palette, drop a Label component on the page, type Choose a File to Upload: and press Enter.
  3. Drag a File Upload component onto the page and drop it underneath the Label component.
  4. 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.
  5. Drag a Label component onto the page and set the text to File Name:
  6. Place a Static Text component to the right of the Label. In the Properties window, set the Static Text's id property to fileNameStaticText.
  7. Drag another Label onto the page. Set the text of the Label to File Type:
  8. Place a Static Text component to the right of the new Label. Set the id of the Static Text to fileTypeStaticText.
  9. 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.
  10. Place an Image component below the Static Text components.
  11. Place a Message Group component below the Image component.

Creating a Folder to Receive the Files

The next step in using the File Upload component is to create a folder in your project to receive the uploaded files. In this example, you save the images to the project-directory\FileUploadExample\web\resources\images directory.
  1. In the Projects window, right-click the FileUploadExample > Web Pages > resources node and choose New > Folder.
  2. Type images in the Folder Name field and click Finish.

    The images folder appears in the Projects window.

Adding Code to Handle Image Uploads

Now that you have the basic file upload form and a place to save the uploaded file, you must add code to handle the file upload.
  1. Double-click the Upload File button and add the following code (shown in bold) to the uploadFileButton_action() method, but note that the code contains errors. You add import statements to fix these errors in the next step. After inserting the code, you can press Ctrl-Shift-F to reformat the code.

    Code Sample 1: 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 {
                    // get the path to the /resources/images directory
                    // from the servlet context
                    ServletContext theApplicationsServletContext =
                        (ServletContext) this.getExternalContext().getContext();
                    String realPath =
                        theApplicationsServletContext.getRealPath
                        ("/resources/images");
                    File file = new File(realPath + File.separatorChar +
                        justFileName);
                    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.");
            }
       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 gets the servlet context and maps the /web/resources/images directory to the actual file system path name on the server. If the file is not a valid image file or if there are other problems uploading the file, an error message is displayed.

  2. 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.
  3. Scroll up to the prerender method node and add the following code, which checks whether there is a file to display:

    Code Sample 2: prerender Method
    public void prerender() {
       String uploadedFileName = (String)
       this.fileNameStaticText.getValue();
       if ( uploadedFileName != null ) {
           String tmpFile = uploadedFileName.replaceAll(" ", "%20");
           image1.setUrl("/resources/images/" + tmpFile);
       }
    }
    

    If there is a file to display, the code replaces spaces in the file name with %20 space characters and then binds the fully qualified file name to the image component. The path /resources/images/ is a context-relative URL. When you precede a URL with a forward slash, you are telling the server to prepend the location of the web application to formulate the complete path.

Testing the Application

  1. Run the application.
  2. Click Browse to navigate through your local drives and select a file to upload. Figure 2 shows the application with an uploaded JPEG file. The image is stored in project-directory\FileUploadExample\build\web\resources\images.

    Figure 2: Application With Uploaded Image
    Figure 2: Application With Uploaded Image
  3. 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.
  1. Create a new Visual Web Application project.
  2. Drag a File Upload component onto the page.
  3. Add a Button component, a Text Area component, and a Message Group component.
  4. Double-click the Button component and add the following action code to the button1_action() method:

    Code Sample 3: 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;
    }
  5. Press Alt-Shift-F to fix imports and automatically add the UploadedFile import statement.
  6. Run the application. Figure 3 shows a sample page.

    Figure 3: Text File Upload 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.
  1. Open the Files window and expand project-name > web > WEB-INF.
  2. Right-click the web-xml node and choose Edit.
  3. In the XML editor, click the Filters button.
  4. Select the maxSize parameter for the UploadFilter, and click the Edit button.
  5. 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.
  6. 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 will be 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/images 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 4: 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, such as

   http://localhost:29080/MyWebApplication/faces/upload/images/myPicture.gif.


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 5: 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 6: 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, see http://java.sun.com/j2se/1.3/docs/api/java/io/File.html.


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.
  1. In the Files window, expand the web node and then expand WEB-INF. Double-click web.xml to open it.
  2. Click the General button and expand Context Parameters, and click the Add button.
  3. 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)
  4. Close and save the web.xml file.
  5. Use the following code:

    Code Sample 7: 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);

See Also:



This page was last modified:  December 6, 2006


Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   GlassFish Community: an Open Source Application Server   Open Solaris  Open JDK: an Open SourceJDK   Mobile & Embedded Community     Sponsored by 
Sponsored by Sun Microsystems