10

I need some help with HTML5. I have a script that loops through all the uploaded files and gets each file details. Currently I am using HTML5 techniques that include FileReader. The FileReader function only works in Chrome and Firefox, so I am looking for an alternative which will work in all of the other browsers.

I saw the Stack Overflow question Flash alternative for FileReader HTML 5 API, but I wasn't able to figure how to use this Flash thing, and aren't there any other solutions so I can loop through all of the uploaded files and get each file details (which will work in Safari and Internet Explorer)?

Community
  • 1
  • 1
AdamGold
  • 4,941
  • 4
  • 29
  • 47
  • 2
    Wouldn't a better question be how to use this flash thing? – Ruan Mendes Apr 06 '11 at 18:05
  • 2
    Well maybe but this flash thing doesn't seem perfect. I would like to get more ideas on alternatives. If anyone could help me set up this flash thing, I would like that too. – AdamGold Apr 09 '11 at 05:36

2 Answers2

4

Ended up not using FileReader at all, instead I looped through event.files and got each file by files[i] and sent an AJAX request by XHR with a FormData object (worked for me because I decided I don't need to get the file data):

var xhrPool = {};
var dt = e.dataTransfer;
var files = (e.files || dt.files);
for (var i = 0; i < files.length; i++) {
    var file = files[i];
    // more code...

    xhrPool[i] = getXMLHttpRequest();
    xhrPool[i].upload.onprogress = uploadProgress;
    initXHRRequest(xhrPool[i], i, file);
    data = initFormData(i, file);

    xhrPool[i].send(data);
}

function initFormData(uploaded, file) {
    var data = new FormData();
    data.append(uploaded, file);
    // parameters...

    return data;
}

function uploadProgress() {
    // code..
}

function initXHRRequest(xhr, uploaded, file) {
    // code... onreadystatechange...
    xhr.open("POST", "ajax/upload.php");
    xhr.setRequestHeader("X-File-Name", file.name);
}

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
}
AdamGold
  • 4,941
  • 4
  • 29
  • 47
2

Safari was the first one to actually implement the HTML5 file API, and there are several demos. Andrea Giammarchi has a nice description on his blog. There are several frameworks to handle this as well which also have fallbacks for Internet Explorer. Fancyupload is one that comes to mind.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cellcortex
  • 3,166
  • 1
  • 24
  • 34
  • 1
    To note: although Fancyupload has graceful degredation, it relies on Flash to work as intended. – Chris Apr 09 '13 at 15:12