Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial

## The fileupload Example Application

The `fileupload` example, located in the tut-install`/examples/web/servlet/fileupload/` directory, illustrates how to implement and use the file upload feature.

The Duke’s Forest case study provides a more complex example that uploads an image file and stores its content in a database.

Note: Except where expressly provided otherwise, the site, and all content provided on or through the site, are provided on an "as is" and "as available" basis. Oracle expressly disclaims all warranties of any kind, whether express or implied, including, but not limited to, the implied warranties of merchantability, fitness for a particular purpose and non-infringement with respect to the site and all content provided on or through the site. Oracle makes no warranty that: (a) the site or content will meet your requirements; (b) the site will be available on an uninterrupted, timely, secure, or error-free basis; (c) the results that may be obtained from the use of the site or any content provided on or through the site will be accurate or reliable; or (d) the quality of any content purchased or obtained by you on or through the site will meet your expectations. Any content accessed, downloaded or otherwise obtained on or through the use of the site is used at your own discretion and risk. Oracle shall have no responsibility for any damage to your computer system or loss of data that results from the download or use of content.

The following topics are addressed here:

- Architecture of the fileupload Example Application

- Running the fileupload Example

### Architecture of the fileupload Example Application

The `fileupload` example application consists of a single servlet and an HTML form that makes a file upload request to the servlet.

This example includes a very simple HTML form with two fields, File and Destination. The input type, `file`, enables a user to browse the local file system to select the file. When the file is selected, it is sent to the server as a part of a POST request. During this process, two mandatory restrictions are applied to the form with input type `file`.

- The `enctype` attribute must be set to a value of `multipart/form-data`.

- Its method must be POST.

When the form is specified in this manner, the entire request is sent to the server in encoded form. The servlet then uses its own means to handle the request to process the incoming file data and extract a file from the stream. The destination is the path to the location where the file will be saved on your computer. Pressing the Upload button at the bottom of the form posts the data to the servlet, which saves the file in the specified destination.

The HTML form in `index.html` is as follows:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>File Upload</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
            <form method="POST" action="upload" enctype="multipart/form-data" >
                File:
                <input type="file" name="file" id="file" /> <br/>
                Destination:
                <input type="text" value="/tmp" name="destination"/>
                </br>
                <input type="submit" value="Upload" name="upload" id="upload" />
            </form>
        </body>
    </html>

A POST request method is used when the client needs to send data to the server as part of the request, such as when uploading a file or submitting a completed form. In contrast, a GET request method sends a URL and headers only to the server, whereas POST requests also include a message body. This allows arbitrary length data of any type to be sent to the server. A header field in the POST request usually indicates the message body’s Internet media type.

When submitting a form, the browser streams the content in, combining all parts, with each part representing a field of a form. Parts are named after the `input` elements and are separated from each other with string delimiters named `boundary`.

This is what submitted data from the `fileupload` form looks like, after selecting `sample.txt` as the file that will be uploaded to the `tmp` directory on the local file system:

    POST /fileupload/upload HTTP/1.1
    Host: localhost:8080
    Content-Type: multipart/form-data;
    boundary=---------------------------263081694432439 Content-Length: 441
    -----------------------------263081694432439
    Content-Disposition: form-data; name="file"; filename="sample.txt"
    Content-Type: text/plain
     Data from sample file
    -----------------------------263081694432439
    Content-Disposition: form-data; name="destination"
     /tmp
    -----------------------------263081694432439
    Content-Disposition: form-data; name="upload"
     Upload
    -----------------------------263081694432439--

The servlet `FileUploadServlet.java` begins as follows:

    @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
        private final static Logger LOGGER =
                Logger.getLogger(FileUploadServlet.class.getCanonicalName());

The `@WebServlet` annotation uses the `urlPatterns` property to define servlet mappings.

The `@MultipartConfig` annotation indicates that the servlet expects requests to be made using the `multipart/form-data` MIME type.

The `processRequest` method retrieves the destination and file part from the request, then calls the `getFileName` method to retrieve the file name from the file part. The method then creates a `FileOutputStream` and copies the file to the specified destination. The error-handling section of the method catches and handles some of the most common reasons why a file would not be found. The `processRequest` and `getFileName` methods look like this:

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            out = new FileOutputStream(new File(path + File.separator
                    + fileName));
            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + path);
            LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
                    new Object[]{fileName, path});
        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                    + "trying to upload a file to a protected or nonexistent "
                    + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

            LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                    new Object[]{fne.getMessage()});
        } finally {
            if (out != null) {
                out.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

### Running the fileupload Example

You can use either NetBeans IDE or Maven to build, package, deploy, and run the `fileupload` example.

The following topics are addressed here:

- To Build, Package, and Deploy the fileupload Example Using NetBeans IDE

- To Build, Package, and Deploy the fileupload Example Using Maven

- To Run the fileupload Example

#### To Build, Package, and Deploy the fileupload Example Using NetBeans IDE

1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

2. From the File menu, choose Open Project.

3. In the Open Project dialog box, navigate to:

       tut-install/examples/web/servlet

4. Select the `fileupload` folder.

5. Click Open Project.

6. In the Projects tab, right-click the `fileupload` project and select Build.

#### To Build, Package, and Deploy the fileupload Example Using Maven

1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

2. In a terminal window, go to:

       tut-install/examples/web/servlet/fileupload/

3. Enter the following command to deploy the application:

       mvn install

#### To Run the fileupload Example

1. In a web browser, enter the following URL:

       http://localhost:8080/fileupload/

2. On the File Upload page, click Choose File to display a file browser window.

3. Select a file to upload and click Open.

   The name of the file you selected is displayed in the File field. If you do not select a file, an exception will be thrown.

4. In the Destination field, type a directory name.

   The directory must have already been created and must also be writable. If you do not enter a directory name or if you enter the name of a nonexistent or protected directory, an exception will be thrown.

5. Click Upload to upload the file that you selected to the directory that you specified in the Destination field.

   A message reports that the file was created in the directory that you specified.

6. Go to the directory that you specified in the Destination field and verify that the uploaded file is present.

Copyright © 2017, Oracle and/or its affiliates. All rights reserved.