Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    VR2
    VR2 is offline
    New Coder
    Join Date
    Jul 2006
    Posts
    39
    Thanks
    0
    Thanked 0 Times in 0 Posts

    AJAX multipart form upload

    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:

    Code:
    // 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)
    			continue;
    			
    		// Skip the ele if its type radio or checkbox and is not "checked"
    		if ((ele.type == "radio" || ele.type == "checkbox") && ele.checked == false)
    			continue;
    		
    		// 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);
    m_XMLHttpRequest.send(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?

  • #2
    Senior Coder A1ien51's Avatar
    Join Date
    Jun 2002
    Location
    Between DC and Baltimore In a Cave
    Posts
    2,717
    Thanks
    1
    Thanked 94 Times in 88 Posts
    You can not upload a file with Ajax. It has to be posted to a hidden iframe.

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint]

  • #3
    VR2
    VR2 is offline
    New Coder
    Join Date
    Jul 2006
    Posts
    39
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •