Home
english
Home
.NET Server
Java Server
.NET Client
AJAX Client
AJAX Browser
Map Drive
Pricing
Contacts
info@ithit.com



Uploading File From a Web Page Using Multipart Form POST

Not all modern browsers support upload from local file system using PUT verb. To overcome this limitation IT Hit Java WebDAV Server supports upload using multipart-encoded form using POST verb.

Note that pausing and restoring broken upload is possible only in rich-client, usually desktop applications, built in Java, .Net, C++/Win32, etc. There is no way to restore broken upload or pause upload in pure Web AJAX application as modern user agents do not provide random-read access to file in local file system. However you can still request upload progress from server in your AJAX code.

To upload a file you must submit a multipart form that contains a single file:

<html>
    <head><title>POST Upload to WebDAV Server</title></head>
    <body>
        <form action="/mydocs/" method="post" enctype="multipart/form-data">
            <input type="file" name="dummyname" /><br />
            <input type="submit" />
        </form>
    </body>
</html>

You must always submit only one file per form without any other input, select or textarea controls. Because of POST standard limitations the server will be unable to calculate file size correctly if any extra controls are submitted. Follow this rules when creating a multipart form:

  1. Specify enctype="multipart/form-data" attribute on a form tag.
  2. Add name attribute to a single input type="file" tag.
  3. DO NOT add name attribute to any other input, select or textarea tags.

Action attribute can specify a folder or a file url. If the file with such name does not exist it will be created. If the file already exists it will be overwritten.

Note that to upload files with non-English and special characters you must specify full file url in action property and url-encode it (action="/mydocs/my%20file.gif"), you cannot upload such file specifying folder url (action="/mydocs/").

The maximum file upload size in most modern browsers is 2Gb.

JavaScript Upload Progress Example

The example below demonstrates how to create a progress bar in JavaScript when uploading a file from a web page. In this example the upload-progress REPORT request is submitted each second using XMLHttpRequest and total file size and amount of bytes uploaded is extracted from a responce. The example runs in Internet Explorer, Firefox, Google Chrome and Safari. See How Resumable Upload Works for upload-progress REPORT description.

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' >
  <head>
    <title>AJAX Upload Progress & Cancel Upload</title>
    <script type='text/javascript'>
        var file;
        function prepareUpload()
        {
            document.getElementById('fileSize').innerHTML = '';
            document.getElementById('bytesUploaded').innerHTML = '';
            document.getElementById('percentUploaded').innerHTML = '';
            document.getElementById('uploadProgressBar').style.width = '0%';
 
            // get file name
            file = document.getElementById('file').value;
            if(file.lastIndexOf('\\')>=0)
                file = file.substr(file.lastIndexOf('\\')+1);
            document.getElementById('fileName').innerHTML = file;
              
            // get folder path
            var curFolder = window.location.href;
            if(curFolder[curFolder.length-1]!='/')
                curFolder = curFolder.substring(0, curFolder.lastIndexOf('/')+1);
 
            document.getElementById('target').innerHTML = curFolder;
            document.getElementById('frm').action = curFolder;
        }
      
        var timerId;
        function formSubmit()
        {
            timerId = setInterval('updateProgress()', 1000);
            document.getElementById('cancelUploadBtn').disabled = false;
        }
      
        function updateProgress()
        {
            var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
            var uploadTarget = document.getElementById("frm").action + file;
          
            request.open("REPORT", uploadTarget, false);
            request.send("<upload-progress xmlns='ithit'/>");
            var resp = request.responseText;
          
            // Extract number of bytes uploaded and total content length of the file.
            // Usually you will use XML DOM or regular expressions for this purposes
            // but here for the sake of simplicity we will just extract using string methods.
            var size;
            var sizeIndex = resp.indexOf("total-content-length");
            if(sizeIndex != -1)
            {
                size = resp.substring(resp.indexOf(">", sizeIndex)+1, resp.indexOf("</", sizeIndex));
                document.getElementById("fileSize").innerHTML = size;
            }
            var bytes = "Finished";
            var percent = 100;
            var bytesIndex = resp.indexOf("bytes-uploaded");
            if(bytesIndex != -1)
            {
                bytes = resp.substring(resp.indexOf(">", bytesIndex)+1, resp.indexOf("</", bytesIndex));
                if(parseInt(size)!=0)
                    percent = 100*parseInt(bytes)/parseInt(size);
            }
 
            document.getElementById("bytesUploaded").innerHTML = bytes;
            document.getElementById("percentUploaded").innerHTML = percent.toString().substr(0, 4) + " %";
            document.getElementById("uploadProgressBar").style.width = percent.toString() + "%";
          
            if(percent==100)
            {
                clearInterval(timerId);
                document.getElementById("cancelUploadBtn").disabled = true;
            }
        }
      
        function cancelUpload()
        {
            // recreate iframe to cancel upload
            document.getElementById("uploadFrameHolder").innerHTML = "<iframe name='uploadFrame' ></iframe>";
            clearInterval(timerId);
            document.getElementById("cancelUploadBtn").disabled = true;
        }
    </script>
  </head>
  <body>
    <span id="uploadFrameHolder" style="display:none"><iframe name="uploadFrame" ></iframe></span>
    
    <form id="frm" method="post" enctype="multipart/form-data" target="uploadFrame" onsubmit="formSubmit()">
        <input type="file" id="file" name="dummyname" onchange="prepareUpload()" /><br />
        <input type="submit" value="Upload" />
    </form>
    <table>
        <tr><td>File Name: </td><td id="fileName"></td></tr>
        <tr><td>Upload Target: </td><td id="target"></td></tr>
        <tr><td>File Size: </td><td id="fileSize"></td></tr>
        <tr><td>Bytes Uploaded: </td><td id="bytesUploaded"></td></tr>
        <tr>
            <td>Upload Progress: </td>
            <td>
                <table>
                    <tr>
                        <td>
                            <div style="width:200px; height:10px; border: solid 1px black; font-size:0px">
                                <div id="uploadProgressBar" style=" background-color: gray; height:100%; width:0%"></div>
                            </div>
                        </td>
                        <td id="percentUploaded"></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <input id="cancelUploadBtn" disabled="true" type="button" value="Cancel" onclick="cancelUpload()" />
  </body>
</html>

 


Selected Customers:
Country: Norway
DnB NOR Group
Country: Finland
Bank of Finland
USA
Symantec
Country: Sweden
Toyota
Country: Denmark
Danfoss Group
Country: USA
Microsoft
Country: Ukraine
Raiffeisen Bank
Country: USA
Siemens
Country: Ukraine
OTP Bank
Country: USA
Intel Corporation
Country: Austria
Austrian Federal Railways
Country: Israel
Autodesk, Inc.
Country: USA
U.S. Customs and Border Protection Agency
Home .NET Server Java Server .NET Client AJAX Client AJAX Browser Map Drive Pricing Contacts

Updated: Monday, February 01, 2010