Fibericon
Fibericon

Reputation: 5793

Uploading problem with XMLHttpRequest Level 2

I'm attempting to upload a file via drag and drop with HTML5. The dragging and dropping bit works no problem - I can get the image I drag to display immediately by dumping the base64 in an img src tag. However, I need to pass the file to the server via POST. In the same request, I also need to pass a unique ID. Here's what my processing function looks like:

function processXHR (file)
{
    var xhr = new XMLHttpRequest(); 
    var fileUpload = xhr.upload;

    fileUpload.addEventListener("progress", uploadProgressXHR, false);

    fileUpload.addEventListener("error", uploadErrorXHR, false);

    xhr.open("POST", "changePicture");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", file.length);

    xhr.sendAsBinary(file.getAsBinary());
    xhr.setRequestHeader("Connection", "close");

}

However, doing this returns an error from codeigniter: "Disallowed Key Characters". Also, it's not sending the unique ID I need. So I changed a few lines:

var params = "card_num="+selected+"&newPicture="+file.getAsBinary();
xhr.open("POST", "changePicture");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.send(params);
xhr.setRequestHeader("Connection", "close");

But that just sends the file as a string. What do I need to be doing here?

Upvotes: 2

Views: 1252

Answers (1)

kreek
kreek

Reputation: 8834

function processXHR(file) {
    var formData = new FormData();
    var xhr = new XMLHttpRequest();

    formData.append(file.name, file);

    xhr.open('POST', "/upload", true);
    xhr.onload = function(e) {
        console.log("loaded!")
    };

    xhr.send(formData);
    return false;
}

Obviously this only works in browsers that support XMLHttpRequest Level 2

Upvotes: 3

Related Questions