FileReader загрузить текстовый файл

239
14 сентября 2018, 15:00

пытаюсь загрузить текстовый файл любого формата через FileReader и не могу получить файл в base64, как делаю с изображениями вот код

/*** 
 * 
 * 
 * function handleFileSelect done next aftet click by button #files  
 * and will across FileReader show image in canvas also create size  
 * if image big 
 * 
 * 
 ***/ 
function handleFileSelect(evt) { //  create funtion handleFileSelect and catch event 
 
    evt.stopPropagation(); // stop event this across page not rebooted 
 
    evt.preventDefault(); // stop event this across page not rebooted 
 
    if (window.File && window.FileList && window.FileReader) { //Check File API support 
 
        var files = event.target.files; // FileList object across click 
 
        var idd = this.className; // area where will show image canvas 
 
        //console.log(this.className); 
 
        var id = parseInt(idd.replace(/\D+/g,"")); 
 
        var output = document.getElementById("result"); // area where will show image canvas 
 
        for (var i = 0; i < files.length; i++) { // Create cycle for variable files.length this quantity files 
 
            var file = files[i]; // variable one each file from cycle 
 
            if (file.type.match('image')){ // Check what load only image 
 
            var picReader = new FileReader(); // create new FileReader 
 
 
            picReader.addEventListener("load", function(event) { // create handler event how only in load image 
 
            var picFile = event.target; // get data object 
 
 
                /*** 
                 * 
                 * 
                 * function etr find heidht image this need if image big 
                 * 
                 * 
                 ***/ 
                function etr() { // create funtion  
 
                    return new Promise((resolve, reject) => { // create asynchronously fuction Promise aross know heigh load image 
 
                        var img = new Image(); // create objet image 
 
                        img.onload = _ => resolve(img.height); // in case of successful load image i will know height  
 
                        img.onerror = reject; // in case of error 
 
                        img.src = picFile.result; // image in base64 
 
                    });// close asynchronously fuction Promise 
 
                };// close funtion etr 
 
 
                (async function() { // launch asynchronously function 
 
                var originalImage = await etr(); // get height image 
 
                    var a = Math.floor(Math.random() * (1000 - 0)) + 0; // create random id for new image 
 
                    var div = document.createElement("div"); // create new div if load new image 
 
                    div.className = 'div_one'; // add class for variable div 
 
                    div.innerHTML = "<div class='col-md-3 " + a + "'><div class='set-btn-d-none " + a + "'><button type='button' value='" + a + "' class='delete'><i class='ion-close-circled'></i></button></div><div class='img-canvas-cnter'><canvas class='previous-imgages' id='" + a + "';></canvas></div></div></div>"; // data that insert div 
                    output.insertBefore(div, null); // whiteher will data variable div 
                    $('.new_Btn').remove(); // delete old block .new_Btn 
                    $('div.col-md-3.'+a ).after('<div class="col-md-3 new_Btn"><i class="ion-plus icon-plus-style"></i></div>'); // add plus after last selector div.col-md-3 
 
                    $(".col-md-3." + a).mousemove(function(event) { // catch event mouse  
                        $(".set-btn-d-none." + a).show(); // if mouse  insert need block show block with buttons 
                    }); // this need for work with canvas image exampe chage size or to turn or delete or show all 
                    $(".col-md-3." + a).mouseout(function(event) { // catch event mouse  
                        $(".set-btn-d-none." + a).hide(); // if mouse not insert block hidden block with buttons 
                    }); // this need for work with canvas image exampe chage size or to turn or delete or show all 
 
 
 
                    var maxHeight = 600; // maximum allowable size height image 
 
                    var canvas = document.getElementById(a); // find need id with canvas 
 
                    var ctd = canvas.getContext("2d"); // create new 2d object 
 
                    if (originalImage < maxHeight) { // check new image more allowable value this variable maxHeight 
 
                        var image = new Image(); // create new object image 
 
                        image.onload = function() { // create function moment load image 
 
                            canvas.width = image.width; //set width canvas 
 
                            canvas.height = image.height; //set height canvas  
 
                            ctd.drawImage(image, 0, 0, image.width, image.height); // create canvas image 
 
                        };// close function image.onload 
 
                        image.src = picFile.result; // data image in base64 
 
                    }// close  check new image more allowable value this variable maxHeight 
 
                    else { // new image more than variable maxHeight 
 
                        var image = new Image(); // create new object image 
 
                        image.onload = function() { // create function moment load image 
 
                            var xImage = image.height / maxHeight; // value for calculating proportions format 16:9 
 
                            var iWidth = image.width / xImage; //new width in format 16:9 
 
                            canvas.width = iWidth; //set width canvas 
 
                            canvas.height = maxHeight; //set height canvas  
 
                            ctd.drawImage(image, 0, 0, iWidth, maxHeight); // create canvas image 
 
                        };// close create function moment load image 
 
                        image.src = picFile.result; // data image in base64 
 
                    }// close new image more than variable maxHeight 
 
                })();// close launch asynchronously function 
 
            });// close Check File API support 
 
            picReader.readAsDataURL(file); //Read the image 
 
            }// check if image 
 
            else if (file.type.match('text.*|application.*')){ // Check what load only text 
 
            var picReader = new FileReader(); // create new FileReader 
 
 
            picReader.addEventListener("load", function(event) { // create handler event how only in load image 
 
            var picFile = event.target;  
 
            console.log(picFile); 
 
           //Read the image 
 
              var a = Math.floor(Math.random() * (1000 - 0)) + 0; // create random id for new image 
 
                    var div = document.createElement("div"); // create new div if load new image 
 
                    div.className = 'div_one'; // add class for variable div 
 
                    var docx = document.getElementById("docx"); // area where will show image canvas 
 
                  // console.log(file); 
 
                    div.innerHTML = "<div class='col-md-3 " + a + "'><div class='set-btn-d-none " + a + "'><button type='button' value='" + a + "' class='delete_doc'><i class='ion-close-circled'></i></button></div><div class='img-canvas-cnter'><img src='http://www.myiconfinder.com/uploads/iconsets/128-128-c0ac799391cf84b99a122a81b0469f39.png'><input class='previous-imgages' id='" + a + "' type='file' name='document[]' value='"+picFile.result+"'></div></div></div>"; 
                     // data that insert div 
                    output.insertBefore(div, null); // whiteher will data variable div 
                    $('.new_Btn').remove(); // delete old block .new_Btn 
                    $('div.col-md-3.'+a ).after('<div class="col-md-3 new_Btn"><i class="ion-plus icon-plus-style"></i></div>'); // add plus after last selector div.col-md-3 
 
                    $(".col-md-3." + a).mousemove(function(event) { // catch event mouse  
                        $(".set-btn-d-none." + a).show(); // if mouse  insert need block show block with buttons 
                    }); // this need for work with canvas image exampe chage size or to turn or delete or show all 
                    $(".col-md-3." + a).mouseout(function(event) { // catch event mouse  
                        $(".set-btn-d-none." + a).hide(); // if mouse not insert block hidden block with buttons 
                    }); // this need for work with canvas image exampe chage size or to turn or delete or show all // this need for work with canvas image exampe chage size or to turn or delete or show all 
               }); 
            picReader.readAsDataURL(file); 
            } 
 
        }// close cycle for 
 
    }// close check for support FileReader API 
 
    else {// if not support FileReader API 
         
        alert("Your browser does not support File API"); // if browser not support FileReader API 
 
    }// close if not support FileReader API 
 
}// close funtion handleFileSelect

READ ALSO
Cordova media stream from camera

Cordova media stream from camera

Есть приложение на cordovaМне надо в приложении использовать камеру для записи видео

188
Рассчитать центр и масштаб карты

Рассчитать центр и масштаб карты

В интерфейсе есть карта на весь экран и на ней 2 точки (lon1, lat1, lon2, lat2)Необходимо рассчитать координаты центра карты (lonC, latC) и масштаб - количество...

129
изменить цвет родителя на дочерний при наведении

изменить цвет родителя на дочерний при наведении

Всем доброго времени суток! Подскажите пожалуйста, нужно чтобы при наведении на div применялся цвет span

177
Webpack. Использование import/export вместо require/module.exports

Webpack. Использование import/export вместо require/module.exports

Как настроить Webpack понимать инструкции import/export вместо синтаксиса CommonJS?

152