Search code examples
javascriptxmlhttprequest

Unable to upload image to server using XMLHttpRequest


I am trying to upload an image to server using using XMLHttpRequest but fails. Below is the code I am using.

 <input type="submit" onclick="fn()" value="Click"/>

 <script type="text/javascript">
function fn(){
  try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    }
    catch (e) {
    console.log("Not firefox");
    }
    xmlhttp = new XMLHttpRequest();
    var requestUrl = "http://localhost:9000/laptop.png";
    xmlhttp.open("GET",requestUrl,true);
    xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status == 200) {
                imageDataPost(xmlhttp.responseText);
                console.log(xmlhttp.responseText);
            }
        }
    } 
    xmlhttp.send();
}

function imageDataPost(imgData) {

    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    }
    catch (e) {
        console.log("Not firefox");
    }

    xmlhttp = new XMLHttpRequest();
    var requestUrl = "http://server_url/fileupload/";
    xmlhttp.open("POST",requestUrl,true);
    xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
    xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status == 200) {
                alert("success");
                console.log(xmlhttp.responseText);
            }
            else {
                alert("Failed");
            }
        }
    } 
    xmlhttp.send("upload="+imgData);        

}

Any Idea whats wrong here. I am getting (an empty string) as response.. File is not uploaded to server. Guys please help.


Solution

  • You simply can't upload a file with pure Javascript (at least not in a cross browser way, see this article for more information)

    This is because XMLHttpRequest has no support for multipart/form-data, you can do tricks like using an iframe or use flash.

    There are enough articles on the internet that explain this.