Flex/JSP Example: Upload video using the Media API

Technology
Media API
Required
Media API token
Edition
Pro, Enterprise

This example illustrates how to upload a video to Brightcove using the Media Write API in a Flex application. It includes client-side and server-side elements:

  • In the client side, VideoUploader.mxml is a Flex application that offers the user a UI for browsing and selecting a video file to upload, provides feedback of the upload progress, and calls a server proxy script to upload the video. In addition, it gets a video id if the Media API call succeeds, or an error message in the case the upload fails.
  • In the server side, it uses a server proxy script, in this case a JSP page (UploaderVideo.jsp) that receives the multipart/form-data from the Flex client, including video name, short and long description, and whether the video should be ad enabled or not. This JSP parses the request and makes the actual call to the create_video Media API.  The API results, including the id of the new video, are sent back to the Flex client.

The Flex app makes use of the FileReference class  to handle all things related to selecting the video file and passing that and the video attributes to the JSP page. If you are not familiar with this class, you might want to read the Flex help docs for a quick review. Before you try this example, make sure that you have all the components installed. All the files you need are contained in FlexVideoUploaderExample.zip:

  1. Flex app.  Extract VideoUploader.zip and import into Flex Builder. Select  Import > Existing Project Into Workspace > Select archive file > VideoUploader.zip. VideoUploader.mxml contains the main application.
  2. UploaderVideo.jsp. Extract uploader.war and deploy it in a web server that supports Java. In Tomcat, for example, you can just drop this war file under your webapps directory and it is automatically deployed.  After that, you should have a new web project folder named uploader. Take a look at the files in this directory. The JSP page is named UploaderVideo.jsp. This JSP uses the ClientHTTPRequest helper class to do the multipart/form-data post to the Media API. This JSP requires the Apache Commons commons-io and commons-fileupload JARs, all included in the war file. You do not need to change this library unless you want to use a different HTTP library to make the multipart post. Also before you run this example, make sure to update UploaderVideo.jsp with your own write API token. Search for the WRITE_API_TOKEN variable and assign the value of your token there. If you do not have a token, please contact Brightcove customer support to request one.

The Flex App

If you have used FileReference before, you will notice that this example basically uses  the three main steps for uploading a file:

  1. Browse and select a file
  2. Call a a server side script after the user has selected a file, and  
  3. Handle the result of the upload.

Browsing for a video file

This action is triggered when the user clicks on the 'Upload' button in uploadForm. The video information has to be filled out. Notice that since we only want to upload video files, a filter (FileFilter) with the common video file extensions is used. This is also the place where we set the handlers for the file selected (Event.SELECT) and upload complete events (DataEvent.UPLOAD_COMPLETE_DATA) in preparation for handling results.

 /**
   * Opens a dialog so the user can select a video file to upload and
   * adds the error and 'video uploaded' handlers
   */
    private function fileBrowse():void {
        fileRef = new FileReference();
        fileRef.addEventListener(Event.SELECT,selectHandler);
        fileRef.addEventListener(Event.COMPLETE,onComplete);
        // Listener for when the server side script is done with the upload.
        fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA ,onUploadCompleteData);
        fileRef.addEventListener(IOErrorEvent.IO_ERROR,onError);            
      
        var videoFilter:FileFilter = 
            new FileFilter ("Video (*.flv,*.mov,*.avi,*.mp4,*.wmv,*.mpeg)",
                                     "*.flv;*.mov;*.avi;*.mp4;*.wmv;*.mpeg"); 
        // We want to upload only video files
        fileRef.browse([videoFilter]);     
    }

Calling the JSP after the user has selected a file

We use the fileReference.upload() method to call the JSP  and we send the video metadata information from the form (name, description, ads enabled, etc) as parameters. The JSP is where we actually make the call to the create_video Media API method. This would be the place where you would add more video metadata such as tags, cue points or reference ids.

private function selectHandler(event:Event): void {
 // Prepare a URL request to the server proxy
 var request:URLRequest = new URLRequest(UPLOAD_VIDEO_URL);
 fileName.text = FileReference(event.target).name;
      
 // Send video attributes selected by the user. The Video Media API 
 // create_video supports several parameters. In this example we limit 
 // those to shortDescription, longDescription, adEnabled, and name.
 // Each attribute name of 'createVideoParams' below
 // should match the name of create_video parameter
 // For a complete list of create_video parameters see:
 // http://docs.brightcove.com/en/media/#Video_Write
var createVideoParams:URLVariables = new URLVariables(); createVideoParams.name=videoName.text; createVideoParams.shortDescription=shortDescription.text; createVideoParams.longDescription =longDescription.text; // When videos are uploaded they are set to ad enabled by default, this // example shows how to upload videos with ads disabled by default createVideoParams.adEnabled = adEnabledCheckBox.selected?"AD_SUPPORTED":"FREE"; var parametersObject:Object = new Object(); request.method = URLRequestMethod.POST; request.data = createVideoParams; fileRef.upload(request); fileUploadProgressBar.visible= true; }

Handling the result of the upload

In onUploadCompleteData, we check if the call to create_video in the JSP side was successful and the video has been uploaded. If the call fails, an error message would be returned.  If you get a video id, it means that your video upload was successful and the video is being processed. You can check the upload status in the Media module or by calling the get_upload_status method of the Media API.
 

    /**
     * Call when UploadVideo.jsp is done processing the upload call.
     * If the call succeeds, the assigned video id can be read
     * from JSONResponse.result
     * if the call fails, an error message with details
     * can be read from JSONResponse.error.message
     */
    private function onUploadCompleteData(event:DataEvent):void {
     trace("onUploadCompleteData");
     var JSONResponse:Object = (JSON.decode(event.data));
   
        if(JSONResponse.error != null && JSONResponse.error != ""){
            videoResult.text = "Error : " + JSONResponse.error.message;
         }else {
            // A successful call returns a JSON response like this
            // {"result": 34414648001, "error";: null, "id": null}
            // Get video id from the result property
            videoResult.text = " Video ID : " + JSONResponse.result;
        }
    }

The Server Side

Between step 2 and 3 above, the JSP page is called. The JSP parses the request sent by the fileReference.upload() to prepare a call to the create_video method. This server proxy is the JSP version of the Java servlet that we have provided in a "Java Example: Video Uploader" previous example of video uploads with HTML and Java. A good explanation of the code can be found there. One difference though, is the addition of the 'ads enabled' flag to upload videos with or without advertising on, and you can add more video metadata fields to this logic.  In addition, this protects your write API token.

What's Next

Although this example demonstrates the basics of using Flex to upload videos to your Brightcove media library, it can be expanded to include more exciting functionality. Here are a couple of ideas, which you can implement:

  • Add support for uploading videos with tags.
  • Create this as an AIR application that allows you to browse and preview your videos before uploading.
  • Add support for cue points.
  • Check the status of your uploads by calling the get_upload_status method of the Media API

We look forward to hearing what you can build!