Saving Uploaded Files via HTML5/Flash Uploader in Other Platforms

Supported technologies: Adobe FlashHTML 5

As you know HTML5/Flash Uploader sends files and additional metadata from client computers to server side in HTTP POST requests. This approach requires a server script to parse the received requests and handle uploaded data. Such script usually extracts files and additional data sent by clients and save them all to file system on a server or handle in some other way. Reading this topic you will learn how to create such scripts in general. Moreover, this topic presents sample upload scripts for the ASP, JSP, and ColdFusion platforms.

Important

An HTTP POST request sent by HTML5/Flash Uploader is not an RFC 1867 request, except when you configure HTML5/Flash Uploader to send original files only.

The main complication of handling POST requests sent by HTML5/Flash Uploader lies in the fact that these requests are not RFC 1867. The reason of this are the following Adobe Flash Player limitations:

  • In Adobe Flash Player there is no standard way to send more than one file (for instance, original file and thumbnails) in a single request other than to prepare this request in memory.
  • If a request was prepared in memory, it is prohibited to send files within such request in Adobe Flash Player.

Because of the specified limitations on the Adobe platform, if you setup HTML5/Flash Uploader to create thumbnails, files and thumbnails will be sent as binary data and will not be recognized as files by a server platform. This topic provides the following information allowing you to overcome these limitations on server side:

Approaches to Saving Uploaded Files

As it is said in the topic introduction there is no standard method of saving uploaded files uploaded by HTML5/Flash Uploader. However, there are two ways to get the files:

Let us consider these methods more closely.

Preprocessing Request

Here you should use a filter which will preprocess an HTTP POST request and make it compatible with the RFC standard before the server upload script runs. After the request is adapted you can treat it as a standard RFC 1867 request and get all the information in the usual way. If your platform allows using JAVA programs as filters (like JSP, JSF or ColdFusion do) it is a good idea to use Aurigma Flash Upload Filter. You can find it in the ColdFusion\Binaries\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\). Later in this topic you will find examples of using Aurigma Flash Upload Filter under JSP and ColdFusion. For information about filters and how to use them, please, see your server platform documentation.

If your server platform does not support JAVA programs as filters you can implement your own filter based on a technology supported by your server. The basic concept of a filter is that the only difference between HTML5/Flash Uploader and standard RFC 1867 requests is the name of filename parameter, which is called filenam_ in HTML5/Flash Uploader requests. The code snippets below show this difference.

Here is a subpart header from an RFC 1867 request:

Content-Disposition: form-data; name="File0_0"; filename="095004.jpg"
Content-Type: image/jpeg

The next header describes the same file, but this header is taken from an HTML5/Flash Uploader request:

Content-Disposition: form-data; name="File0_0"; filenam_="095004.jpg"
Content-Type: image/jpeg

Extracting Binary Data and Saving It to File

In this case you do not need to preprocess requests. To save an uploaded file you should implement the following steps in your upload script:

  1. Get the request sent by HTML5/Flash Uploader.
  2. Obtain binary data from the FileX_0 request field, where X is an ordinal number of converter.
  3. Save this data as a file.

You can also get additional information from the request fields, for the full list of fields see the POST Field Reference.

Uploading Original Files Only

Here we consider the case when HTML5/Flash Uploader is configured to send source files only. The configuration of HTML5/Flash Uploader should be as follows:

JavaScript
var fu = $au.imageUploaderFlash({
    id: 'Uploader1',
    converters: [
    {mode: '*.*=SourceFile'}
    ]
});

In this, and only this, case the request sent by HTML5/Flash Uploader is a standard RFC 1867 request, so you can use usual for your platform components to get files, for instance:

  • ASPUpload or Dundas Upload in ASP
  • FileUpload in JSP
  • <cffile> in ColdFusion

Client-Side Configuration

All the server-side upload scripts considered in this topic is designed having in mind that HTML5/Flash Uploader is configured to send SourceFile as first converted file and Thumbnail as the second one. The following code snippet shows such configuration:

JavaScript
var fu = $au.imageUploaderFlash({
    id: 'Uploader1',
    converters: [
    {mode: '*.*=SourceFile'},
    {mode: '*.*=Thumbnail'}
    ]
});

If you send some other set of converted files, the server scripts can be easily adapted to your configuration.

Upload Script Sample for ASP

The upload script considered here parses received request and saves binary data uploaded in FileX_0 request fields as files. The script uses the following third-party classes: clsUpload and clsField; you can find instructions on how to get and use them in the ASP\Instruction.txt file in the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\). The clsUpload class retrieves multi-part form data posted to web page and returns it as a set of clsField instances (each one corresponds to a field in the request). Whereas the clsField class provides the SaveAs method, which saves field content as a binary file with the given name.

Visual Basic
<%@  language="VBScript" %>
<!--#INCLUDE FILE="clsUpload.asp"-->
<%
Server.ScriptTimeout = 450

'This variable specifies relative path to the folder, where the gallery with uploaded files is located.
'Do not forget to put a slash in the end of the folder name.
Dim strGalleryPath
strGalleryPath = "../Gallery/"

' Instantiate Upload Class
Set objUpload = New clsUpload


' Grab the file name
Dim strFileName, strPath
strFileName = objUpload.Fields("SourceName_0").Value

' Save source file
strPath = Server.MapPath(strGalleryPath & strFileName)
objUpload("File0_0").SaveAs strPath

'Save thumbnail
strPath = Server.MapPath(strGalleryPath & "Thumbnails/" & strFileName & ".jpg")
objUpload("File1_0").SaveAs strPath

' Release upload object from memory
Set objUpload = Nothing

Response.Write("ok")
%>

You can find full source code of this and other samples in the ASP\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\).

Upload Script Sample for JSP

To preprocess an HTML5/Flash Uploader request in JSP we recommend you to use Aurigma Flash Upload Filter. You can find the filter in the JSP\Binaries\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\). In order to utilize the filter you need to:

  1. Register UploadFilter in your application's web.xml file by adding the following code:
  2. XML
    <filter>
        <description>Fix Aurigma HTML5/Flash Uploader request</description>
        <filter-name>UploadFilter</filter-name>
        <filter-class>com.aurigma.imageuploaderflash.UploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>UploadFilter</filter-name>
        <url-pattern>/upload.jsp</url-pattern>
    </filter-mapping>
    
  3. Add Aurigma.ImageUploaderFlash.jar file to your web application.

When an HTML5/Flash Uploader request is adapted you can use any library to handle uploaded files: save files to disk, write additional data to database, or carry out any other operations.

Here we consider an open-source package called Apache Commons-FileUpload. The package is developed by the Apache Software Foundation, and you can find the most recent version of FileUpload at the following location: http://commons.apache.org/proper/commons-fileupload/.

Our upload script uses the following two classes belonging to the FileUpload package: DiskFileItemFactory and ServletFileUpload. The ServletFileUpload class handles multiple files per single HTML widget, using an instance of DiskFileItemFactory to determine how the data for individual parts is stored. When you call the parseRequest method of the ServletFileUpload class, it returns a list of FileItem class instances that represent uploaded files and POST fields. Finally, script saves uploaded files (an original file and its thumbnail) to the disk.

Pay attention that the script expects that HTML5/Flash Uploader configuration is the same as the mentioned above.

C#
<%@page import="org.xml.sax.SAXException"%>
<%@page import="javax.xml.parsers.ParserConfigurationException"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"
import="java.io.*,java.util.*,javax.servlet.*,javax.servlet.http.*,org.apache.commons.fileupload.*,org.w3c.dom.*,org.w3c.dom.ls.*"%>

<%!
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget to put a slash in the end of the folder name.
   String galleryPath = "Gallery/";
   String absGalleryPath;
   String absThumbnailsPath;
   String absTempPath;
%>
<%
   //Process request.
   ServletContext context = getServletContext();
   absGalleryPath = context.getRealPath(galleryPath);
   absThumbnailsPath = context.getRealPath(galleryPath + "/Thumbnails");
   absTempPath = context.getRealPath(galleryPath + "/Temp");

   // Create a factory for disk-based file items
   FileItemFactory factory = new DiskFileItemFactory(10240, new File(absTempPath));

   // Create a new file upload handler
   ServletFileUpload upload = new ServletFileUpload(factory);

   // Parse the request
   List listFileItems = upload.parseRequest(request);

   //Put them in hash table for fast access.
   Hashtable fileItems = new Hashtable();

   for (int i = 0; i < listFileItems.size(); i++) {
      FileItem fileItem = (FileItem) (listFileItems.get(i));
      fileItems.put(fileItem.getFieldName(), fileItem);
   }

	//Get source file and save it to disk.
	FileItem sourceFileItem = (FileItem) fileItems.get("File0_0");
	String fileName = new File(sourceFileItem.getName()).getName();
	File sourceFile = new File(absGalleryPath + File.separator + fileName);
	sourceFileItem.write(sourceFile);

	//Get first and only thumbnail and save it to the disk.
	FileItem thumbnail1FileItem = (FileItem) fileItems.get("File1_0");
	File thumbnail1File = new File(absThumbnailsPath + File.separator + fileName + ".jpg");
	thumbnail1FileItem.write(thumbnail1File);
%>

You can find full source code of this and other samples in the JSP\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\).

Upload Script Sample for ColdFusion

Here we use Aurigma Flash Upload Filter to preprocess a request received from HTML5/Flash Uploader. You can find it in the ColdFusion\Binaries\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\). To install the filter under ColdFusion you should perform the following steps:

  1. Copy Aurigma.ImageUploaderFlash.jar file into the <cf_root>\wwwroot\WEB-INF\lib\ directory (usually it is C:\ColdFusion9\wwwroot\WEB-INF\lib\ on Windows).
  2. Add the following code to the web.xml file in the wwwroot\WEB-INF\ folder of the ColdFusion Server (usually it is C:\ColdFusion9\wwwroot\WEB-INF\ on Windows):
  3. XML
    <!-- HTML5/Flash Uploader Filter -->
    <filter>
        <description>Fix Aurigma HTML5/Flash Uploader request</description>
        <filter-name>UploadFilter</filter-name>
        <filter-class>com.aurigma.imageuploaderflash.UploadFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>UploadFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  4. Restart the ColdFusion Service.

After the filter is installed you can use the ColdFusion tag <cffile>, which provides all the functionality we need to save uploaded files. Name of the request field, the folder where save file to, and what to do in case of file name collision can be specified via <cffile> attributes.

The following upload script "assumes" that HTML5/Flash Uploader is configured in the way considered above.

XML
<cfprocessingdirective pageEncoding="utf-8">
<!---This variable specifies relative path to the folder, where the gallery with uploaded files is located.
Do not forget to put a slash in the end of the folder name.--->
<cfset galleryPath="Gallery/" />
		
<cfset absGalleryPath="#ExpandPath(galleryPath)#" />
<cfset absThumbnailsPath="#absGalleryPath#Thumbnails/" />
			
<!--- Get source file and save it to disk. --->
<cffile action="UPLOAD" filefield="File0_0" 
	destination="#absGalleryPath#" 
	nameconflict="MakeUnique">
	
<cfset fileName="#serverFile#">

<!--- Get first and only thumbnail and save it to the disk. --->
<cffile action="UPLOAD" filefield="File1_0" 
	destination="#absThumbnailsPath#" 
	nameconflict="MakeUnique">

<!--- Rename thumbnail file so that it has .jpg extension --->
<cffile action="rename"
	source="#absThumbnailsPath#/#serverFile#"
	destination="#absThumbnailsPath#/#fileName#.jpg">

You can find full source code of this and other samples in the ColdFusion\ subfolder of the HTML5/Flash Uploader installation folder (usually it is C:\Program Files\Aurigma\Upload Suite 8.5.67\HTML5-Flash\).

See Also

Reference

Other