Vaadin

Join Vaadin Log In

The Upload component allows a user to upload files to the server. It displays a file name entry box, a file selection button, and an upload submit button. The user can either write the filename in the text area or click the Browse button to select a file. After the file is selected, the user sends the file by pressing the upload submit button.

// Create the Upload component.
Upload upload = new Upload("Upload the file here", this);

You can set the text of the upload button with setButtonCaption(), as in the example above, but it is difficult to change the look of the Browse button. This is a security feature of web browsers. The language of the Browse button is determined by the browser, so if you wish to have the language of the Upload component consistent, you will have to use the same language in your application.

upload.setButtonCaption("Upload Now");

The uploaded files are typically stored as files in a file system, in a database, or as temporary objects in memory. The upload component writes the received data to an java.io.OutputStream so you have plenty of freedom in how you can process the upload content.

To use the Upload component, you need to define a class that implements the Upload.Receiver interface. The receiveUpload() method is called when the user clicks the submit button. The method must return an OutputStream. To do this, it typically creates a File or a memory buffer where the stream is written. The method gets the file name and MIME type of the file, as reported by the browser.

When an upload is finished, successfully or unsuccessfully, the Upload component will emit the Upload.FinishedEvent event. To receive it, you need to implement the Upload.FinishedListener interface, and register the listening object in the Upload component. The event object will also include the file name, MIME type, and length of the file. Notice that the more specific Upload.FailedEvent and Upload.SucceededEvent events will be called in the cases where the upload failed or succeeded, respectively.

The following example allows uploading images to /tmp/uploads directory in (UNIX) filesystem (the directory must exist or the upload fails). The component displays the last uploaded image in an Embedded component.

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.vaadin.terminal.FileResource;
import com.vaadin.ui.*;
public class MyUploader extends CustomComponent
                        implements Upload.SucceededListener,
                                   Upload.FailedListener,
                                   Upload.Receiver {
    Panel root;         // Root element for contained components.
    Panel imagePanel;   // Panel that contains the uploaded image.
    File  file;         // File to write to.
    MyUploader() {
        root = new Panel("My Upload Component");
        setCompositionRoot(root);
        // Create the Upload component.
        final Upload upload =
                new Upload("Upload the file here", this);
        // Use a custom button caption instead of plain "Upload".
        upload.setButtonCaption("Upload Now");
        // Listen for events regarding the success of upload.
        upload.addListener((Upload.SucceededListener) this);
        upload.addListener((Upload.FailedListener) this);
        root.addComponent(upload);
        root.addComponent(new Label("Click 'Browse' to "+
                "select a file and then click 'Upload'."));
        // Create a panel for displaying the uploaded image.
        imagePanel = new Panel("Uploaded image");
        imagePanel.addComponent(
                         new Label("No image uploaded yet"));
        root.addComponent(imagePanel);
    }
    // Callback method to begin receiving the upload.
    public OutputStream receiveUpload(String filename,
                                      String MIMEType) {
        FileOutputStream fos = null; // Output stream to write to
        file = new File("/tmp/uploads/" + filename);
        try {
            // Open the file for writing.
            fos = new FileOutputStream(file);
        } catch (final java.io.FileNotFoundException e) {
            // Error while opening the file. Not reported here.
            e.printStackTrace();
            return null;
        }
        return fos; // Return the output stream to write to
    }
    // This is called if the upload is finished.
    public void uploadSucceeded(Upload.SucceededEvent event) {
        // Log the upload on screen.
        root.addComponent(new Label("File " + event.getFilename()
                + " of type '" + event.getMIMEType()
                + "' uploaded."));
        
        // Display the uploaded file in the image panel.
        final FileResource imageResource =
                new FileResource(file, getApplication());
        imagePanel.removeAllComponents();
        imagePanel.addComponent(new Embedded("", imageResource));
    }
    // This is called if the upload fails.
    public void uploadFailed(Upload.FailedEvent event) {
        // Log the failure on screen.
        root.addComponent(new Label("Uploading "
                + event.getFilename() + " of type '"
                + event.getMIMEType() + "' failed."));
    }
}

The example does not check the type of the uploaded files in any way, which will cause an error if the content is anything else but an image. The program also assumes that the MIME type of the file is resolved correctly based on the file name extension. After uploading an image, the component will look as show in Figure 5.42, “Image Upload Example” below. The browser shows the Browse button localized.


Table of Contents

Preface
1. Introduction
1.1. Overview
1.2. Example Application Walkthrough
1.3. Support for the Eclipse IDE
1.4. Goals and Philosophy
1.5. Background
2. Getting Started with Vaadin
2.1. Installing Vaadin
2.2. Setting up the Development Environment
2.3. QuickStart with Eclipse
2.4. Your First Project with Vaadin
3. Architecture
3.1. Overview
3.2. Technological Background
3.3. Applications as Java Servlet Sessions
3.4. Client-Side Engine
3.5. Events and Listeners
4. Writing a Web Application
4.1. Overview
4.2. Managing the Main Window
4.3. Child Windows
4.4. Handling Events with Listeners
4.5. Referencing Resources
4.6. Shutting Down an Application
4.7. Handling Errors
4.8. Setting Up the Application Environment
5. User Interface Components
5.1. Overview
5.2. Interfaces and Abstractions
5.3. Common Component Features
5.4. Label
5.5. Link
5.6. TextField
5.7. RichTextArea
5.8. Date and Time Input
5.9. Button
5.10. CheckBox
5.11. Selecting Items
5.12. Table
5.13. Tree
5.14. MenuBar
5.15. Embedded
5.16. Upload
5.17. Form
5.18. ProgressIndicator
5.19. Slider
5.20. Component Composition with CustomComponent
6. Managing Layout
6.1. Overview
6.2. Window and Panel Root Layout
6.3. VerticalLayout and HorizontalLayout
6.4. GridLayout
6.5. FormLayout
6.6. Panel
6.7. SplitPanel
6.8. TabSheet
6.9. Accordion
6.10. Layout Formatting
6.11. Custom Layouts
7. Visual User Interface Design with Eclipse (experimental)
7.1. Overview
7.2. Creating a New CustomComponent
7.3. Using The Visual Editor
7.4. Structure of a Visually Editable Component
8. Themes
8.1. Overview
8.2. Introduction to Cascading Style Sheets
8.3. Creating and Using Themes
8.4. Creating a Theme in Eclipse
9. Binding Components to Data
9.1. Overview
9.2. Properties
9.3. Holding properties in Items
9.4. Collecting items in Containers
10. Developing Custom Components
10.1. Overview
10.2. Doing It the Simple Way in Eclipse
10.3. Google Web Toolkit Widgets
10.4. Integrating a GWT Widget
10.5. Defining a Widget Set
10.6. Server-Side Components
10.7. Using a Custom Component
10.8. GWT Widget Development
11. Advanced Web Application Topics
11.1. Special Characteristics of AJAX Applications
11.2. Application-Level Windows
11.3. Embedding Applications in Web Pages
11.4. Debug and Production Mode
11.5. Resources
11.6. Shortcut Keys
11.7. Printing
11.8. Portal Integration
11.9. Google App Engine Integration
11.10. Common Security Issues
11.11. URI Fragment and History Management with UriFragmentUtility
11.12. Capturing HTTP Requests
A. User Interface Definition Language (UIDL)
A.1. API for Painting Components
A.2. JSON Rendering
B. Songs of Vaadin
Index