Uploading and Downloading Files

File and Stream Guide: [ nsIScriptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ]

Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome!

Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes.

The IO object and stream objects can be used to upload files to servers in various ways. The exact method depends on the type of upload that you wish to perform.

HTTP File Upload

Some web sites allow one to upload a file. This is done by using an HTML <input> element using the file type from within a form. When the user selects a file, it can be uploaded to a server. This operation can also be performed via a script using the XMLHttpRequest object. This is a common technique for uploading files as it is compatible with existing servers and FormData interface makes that task fairly simple.

A FormData object will automatically generate request data with MIME type multipart/form-data that existing servers can process. To add a file field to the data you use a File object that an extension can construct from file path. The FormData object can then simply be passed to XMLHttpRequest:

function upload(postUrl, fieldName, filePath)
{
  var formData = new FormData();
  formData.append(fieldName, new File(filePath));

  var req = new XMLHttpRequest();
  req.open("POST", postUrl);
  req.onload = function(event) { alert(event.target.responseText); };
  req.send(formData);
}

HTTP PUT

You can also upload a file using an HTTP PUT operation. This is simpler but it doesn't allow sending additional data and web servers usually need special configuration to support PUT operations.

function uploadPut(postUrl, filePath)
{
  var req = new XMLHttpRequest();
  req.open("PUT", postUrl);
  req.setRequestHeader("Content-type", "text/plain");
  req.onload = function(event) { alert(event.target.responseText); }
  req.send(new File(filePath));
}

In this example, a new input stream is created for a file, and is passed to the XMLHttpRequest's send method.

Downloading Files

Under construction... Meanwhile you can read this.

Document Tags and Contributors

Contributors to this page: gal007, Wladimir_Palant, andpol, Nickolay, trevorh, Enn, MarkFinkle, Waldo
Last updated by: gal007,