View Full Version : AJAX multipart form upload

07-07-2006, 02:09 PM
How do you use the XMLHttpRequest object to Post binary file data to the server?

What I mean is, posting normal "string" values from a form is easy, you iterate over the form fields, and create your Data for posting:

// Package up form data
var dataString = "";
if (dataForm)
var eleColl = dataForm.elements;
for (var i = 0; i < eleColl.length; i++)
var ele = eleColl[i];

// If no ele name then continue, some form elements may not be needed, we take only those with a name
if (!ele.name)

// Skip the ele if its type radio or checkbox and is not "checked"
if ((ele.type == "radio" || ele.type == "checkbox") && ele.checked == false)

// Add in a seperator if needed.
if (dataString != "")
dataString += "&";

// Use the JS escape function to escape the var name and value
dataString += escape(ele.name) + "=" + escape(ele.value);

// Send via GET or POST
if (method == "GET") // Append data to URL
url == "?" + dataString;

// Open the url
m_XMLHttpRequest.open(method, url, true);
// Set the standard form headers
m_XMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// Send the data
if (CCObj.m_DebugXMLHttpRequest)
alert("Call send with this data:\n\n" + dataString);

But how on earth do you tackle a File field, its not like you can even access the value of it, let alone access the disk and get the bytes, and then format the Post data.

Any takers?

07-07-2006, 04:44 PM
You can not upload a file with Ajax. It has to be posted to a hidden iframe.


07-07-2006, 05:23 PM
Ok thanks for the quick & definitive response.

I didn't see how it could be possible, hence the question...I think it must be all the AJAX hype, it makes you kinda think it must be a cure all :)