Simple AJAX File Uploader

This JavaScript article tutorial guides us how to use AJAX to create a simple file uploader. Please go to the inner post page for full completed details, instructions and JavaScript source codes.

Sampled by ©

This article described how to create file Upload form using AJAX technology.


File uploading thru HTTP is always big problem for websites. There are some restrictions from client and server sides. But with growing internet channels bandwidth one of major problem is file size. Sometimes itís impossible to send 500MB file to webserver due to request length limit. One of the workaround is to increase maximal request length on webserver, but it may cause server restart when memory limit will be exceeded. For example: IIS APS.NET webserver. We increases maxRequestLength to 500MB, memoryLimit default value is 60% it means that process will be recycled when it use more than 60% of physical memory. If we have 1GB of physical memory in system and couple of users uploads simultaneously 400MB files webserver will be restarted with very high chance, because server wouldnít have time to release memory from Requests objects.

Another big issue is file upload continuing, when process was interrupted by some reasons. Normally user needs to upload whole file once again

In this example Iíll describe how to implement file uploading method using AJAX and WebService technologies. Of course this method has its own restrictions, but it would be quite useful for intranet solutions and administrative areas in internet websites.

How it works

Main idea is quite simple. We should read file partially on send these parts to webserver.

Client Side

//Receive intial file information and init upload

function getFileParams()


 //Convert file path to appropriate format

 this.filePath = document.getElementById("file").value.replace(//g, "\"); fso = new ActiveXObject( 'Scripting.FileSystemObject' );

 if ( !fso.FileExists(this.filePath) )


  alert("Can't open file.");



f = fso.GetFile( this.filePath );

 this.fileSize = f.size;

 this.fileName = f.Name;




Allocate file on client, get file size. I use Scripting.FileSystemObject ActiveX object to get file size because this object will not load full file in memory.
Then init form Layout and upload process by InitStatusForm() and InitUpload functions.

function InitUpload()


 document.getElementById("uploadConsole").style.display = "none";

 document.getElementById("statusConsole").style.display = "block"; xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );

 xmlhttp.onreadystatechange = HandleStateChange;

var parameters = "fileSize=" + encodeURI(this.fileSize) +

 "&fileName=" + encodeURI(this.fileName)+

 "&overwriteFile=" + encodeURI(document.getElementById("overwriteFile").checked);"POST","http://localhost/AJAXUpload/Upload.asmx/InitUpload", true);


 xmlhttp.setRequestHeader("Content-length", parameters.length);

 xmlhttp.setRequestHeader("Connection", "close");



Init upload: Create XmlHttp object and send to webservice initial information such file size, file name and overwrite flag.

//XMLHTTPRequest change state callback function

function HandleStateChange() {

 switch (xmlhttp.readyState) {

 case 4:

  response  = xmlhttp.responseXML.documentElement;

  id = response.getElementsByTagName('ID')[0];

  offset = esponse.getElementsByTagName('OffSet')[0];

  bufferLength = response.getElementsByTagName('BufferLength')[0];  percentage = (offset/this.fileSize)*100;

  if (offset<this.fileSize && !this.cancelUpload)


   UpdateStatusConsole(percentage, "Uploading");

   SendFilePart(offset, bufferLength);





   if (this.cancelUpload)

    UpdateStatusConsole(percentage, "Canceled");


    UpdateStatusConsole(percentage, "Complete");





Asynchronous request from server-side handled by HandledStateChange() callback function.
Parse parameters from server: id Ė response-request identifier, offset Ė start position to read file part. bufferLength Ė file block size to read.
If requested start position not exceed file size and upload not canceled by user we send file part.

//Read part of file and send it to webservice

function SendFilePart(offset, length)


 // create SOAP XML document

 var xmlSOAP = new ActiveXObject("MSXML2.DOMDocument");

 xmlSOAP.loadXML('<?xml version="1.0" encoding="utf-8"?>'+

 '<soap:Envelope xmlns:xsi="" '+

 'xmlns:xsd="" xmlns:soap=""> '+


   '<UploadData xmlns="" >'+






 '</soap:Envelope>'); // create a new node and set binary content

 var fileNode = xmlSOAP.selectSingleNode("//file");

 fileNode.dataType = "bin.base64";

 // open stream object and read source file

 if (adoStream.State != 1 )


  adoStream.Type = 1;  // 1=adTypeBinary 




adoStream.Position = offset;

 // store file content into XML node

 fileNode.nodeTypedValue = adoStream.Read(length);//adoStream.Read(-1); // -1=adReadAll

 if (adoStream.EOS)


  //Close Stream



// send XML document to Web server

 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

 xmlhttp.onreadystatechange = HandleStateChange;"POST", "http://localhost/AJAXUpload/Upload.asmx", true);

 xmlhttp.setRequestHeader("SOAPAction", "");

 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");



In this function we create XmlSoap, read file part using ADODB.Stream ActiveX object and send it to WebServer with file name and filesize.
Server response from this operation would be handled by the same HandledStateChange() callback function.

Server Side


public XmlDocument InitUpload(int fileSize, string fileName, bool overwriteFile )


 long offset = 0;

 string filePath = GetFilePath(fileName); if (File.Exists(filePath))


  if (overwriteFile)






   using (FileStream fs = File.Open(filePath, FileMode.Append))


    offset = fs.Length;




return GetXmlDocument(Guid.NewGuid(), string.Empty, offset,



Init upload server-side function. If file with such name already exist and overwrite flag is false existed file will be appended otherwise file will be deleted. Then construct response by GetXmlDocument function.


public XmlDocument UploadData(string fileName, int fileSize, byte[] file)


 if (fileName == null || fileName == string.Empty || file == null)

  return GetXmlDocument(Guid.NewGuid(), "Incorrect UploadData Request", 0, 0); string filePath = GetFilePath(fileName);

long offset=0;

 using (FileStream fs = File.Open(filePath, FileMode.Append))


  fs.Write(file, 0, file.Length);

  offset = fs.Length;


 return GetXmlDocument(Guid.NewGuid(), string.Empty, offset,



This method handle request from client with file part data. Append file part to uploaded part and request next part.

Install and Run

To run project you should done couple manipulations:
1. Give read/write permissions to your IIS user for Upload folder.
2. Enable ActiveX objects in your IE browser. (Add website to trusted websites)


Iíve described solution core all Layout functionality like upload panel and progress bar can be founded in project.

Please donít use this solution AS IS in your projects. Itís just AJAX upload form example.
Working with streams, files and ActiveX objects expects handles all error cases.

Links Ė Excellent AJAX article. Ė File upload technique.

Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB
WordPress Landing Page Conversion Essentials to Convert More
4 Development Hacks To Make Your Website Launch A Success
Why Data Recovery Software and Services are Important
Why Engineers Specializing in DevOps Are the Wave of the Future

Top view articles
Top 10 Beautiful Christmas Countdown Timers
65 Free JavaScript Photo Gallery Solutions
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
Top 10 Free Web Chat box Plug-ins and Add-ons
Top 10 Best JavaScript eBooks that Beginners should Learn
50+ Beautiful Resources of HTML Form using CSS and JavaScript
The Ultimate JavaScript Tutorial in Web Design
HTML5 Web Workers Multithreading in JavaScript
Learn more about JavaScript Inheritance with Tiny JavaScript Example Codes

Free JavaScript Tutorials & Articles