Sunday, February 1, 2015

how to upload csv file to server via ajax in javascript


how to upload csv file to server via ajax in javascript




dropContainer.addEventListener('drop',function(evt){
    evt.stopPropagation();//stop event bubble
    evt.preventDefault(); // stop event bubble
    //iterate through the files
    Array.prototype.forEach.call(evt.dataTransfer.files, function (currentData) {
        //currentData - File - current file object of evt.dataTransfer.files
        filereader = new FileReader; // create a file reader
        //define when load ends listener
        filereader.onloadend = function(){
            contenArea.innerHTML += filereader.result;
        }
        filereader.readAsText(currentData);//start reading the file

      //=====   IF you want to send the form data to server ===
        // create a form data , you can retrieve the file in  PHP    via  $_FILES['uploadedFile']
        var tempFormData = new FormData;
        tempFormData.append("uploadedFile", currentData);
        // prepare ajax content and sendfile
        xhr = new XMLHttpRequest();
         //gets called everytime there is a state change
        xhr.onreadystatechange = function () {
            if (xhr.status === 4) {
                console.log("done uploading");
            }
        };
         // configure the xhr
        xhr.open("POST", "http://localhost:8000");
        // send the form data
        xhr.send(tempFormData);
    });

});

No comments:

Post a Comment