Загрузка нескольких файлов с использованием ajax с предварительным изменением размера

У меня есть функция с предварительным изменением размера и загрузкой файла ajax. Я вызываю эту функцию в букле FOR в зависимости от размера входного файла. Когда я позвоню это один раз. Работает нормально, но иногда (я не знаю, почему только иногда), когда я вызываю это несколько раз, функция загружает дубликаты изображений. Может быть, для следующего, когда предыдущий еще не закончен и использует тот же холст? Как я могу это исправить? Большое спасибо!

Вот мой код:

...

for (var i = 0; i < filesToUpload.length; i++) {
   j=j+1;
   preandupload(filesToUpload[i],filesToUpload.length,j);
}
...

function preandupload(file,cuantos,actual){

var dataurl = null;
var img=null;
var canvas=null;
var ctx=null;
// Create an image
img = new Image();


// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onloadend = function(e)
{
    img.src = e.target.result;

    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.id = "mycanvas"+actual;
        var ctx = canvas.getContext("2d");

        ctx.drawImage(img, 0, 0);


        var MAX_WIDTH = 1280;
        var MAX_HEIGHT = 1280;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var fd = new FormData();
        getOrientation(file, function(orientation) {

        ctx.drawImage(img, 0, 0, width, height);

        dataurl = canvas.toDataURL("image/jpeg",0.6);

        // Post the data

        fd.append("ori", orientation);
        fd.append("image", dataurl);

        $.ajax({
            url: 'savetofile.php',
            data: fd,
            cache: false,
            contentType: false,
            processData: false,
            enctype: 'multipart/form-data',
            type: 'POST',
            success: function(data){

               uploadComplete2(cuantos,actual)


            }
        });
      });



    } // img.onload
 }
// Load files into file reader
reader.readAsDataURL(file);
}

person Eduardo López    schedule 26.02.2016    source источник


Ответы (1)


вы можете использовать плагин plUpload для загрузки нескольких файлов с изменением размера на стороне клиента. http://www.plupload.com/docs/Image-Resizing-on-Client-Side должен выглядеть примерно так, как показано ниже. В этом коде я уменьшаю качество изображения в зависимости от размера файла. вы можете обратиться по ссылке выше для изменения размера изображения.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plupload - Custom example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- production -->
<script type="text/javascript" src="../js/plupload.full.min.js"></script>
<!-- debug 
<script type="text/javascript" src="../js/moxie.js"></script>
<script type="text/javascript" src="../js/plupload.dev.js"></script>
-->
<style type="text/css">
    .spacer
    {
        float: none;
        clear: both;
        height: 10px;
    }
    #filelist
    {
        background: #ADADAD;
    }
    #filelist ul
    {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    #filelist li
    {
        list-style: none;
        float: left;
        padding: 5px;
    }
    #filelist li .img_preview
    {
        display: block;
        height:100px;
        width: 100px;
        border: 1px solid #666666;
    }

</style>
</head>
<body style="font: 13px Verdana; background: #eee; color: #333">

<h1>Custom example</h1>

<p>Shows you how to use the core plupload API.</p>

<div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div>
<div class="spacer"></div>
<br />

<div id="container">
    <a id="pickfiles" href="javascript:;">[Select files]</a> 
    <a id="uploadfiles" href="javascript:;">[Upload files]</a>
</div>

<br />
<pre id="console"></pre>


<script type="text/javascript">
var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'pickfiles', // you can pass an id...
    container: document.getElementById('container'), // ... or DOM Element itself
    url : 'upload.php',
    flash_swf_url : '../js/Moxie.swf',
    silverlight_xap_url : '../js/Moxie.xap',

    filters : {
        max_file_size : '10mb',
        mime_types: [
            {title : "Image files", extensions : "jpg,gif,png"},
            {title : "Zip files", extensions : "zip"}
        ]
    },

    init: {
        PostInit: function() {
            document.getElementById('filelist').innerHTML = '<ul></ul>';
            document.getElementById('uploadfiles').onclick = function() {
                uploader.start();
                return false;
            };
        },
        UploadProgress: function(up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        },

        Error: function(up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
        },
        BeforeUpload: function(up, file)
        {
            console.log(file.name+"::"+file.origSize);

            if(file.origSize>=800000)
            {
                console.log("resize 80000: 50");
                up.setOption('resize',{enabled:true,quality:50});
            }
            else if(file.origSize>=700000)
            {
                console.log("resize 70000: 55 ");
                up.setOption('resize',{enabled:true,quality:55});
            }
            else if(file.origSize>=600000)
            {
                console.log("resize 60000: 60");
                up.setOption('resize',{enabled:true,quality:60});
            }
            else
            {
                console.log("resize desabled");
                up.setOption('resize',false);
            }
        }
    },
    resize: {
      enabled: true
    },

});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
    $.each(files, function(i){

        var img = new moxie.image.Image();
        $('#filelist').append("<li id='"+this.id+"'><span class='img_preview'></span><br><i>"+this.name+"</i><br><b>Not Uploaded</b></div>");
        img.onload = function() {
            this.embed($('#filelist li:eq('+i+') span').get(0), {
                width: 100,
                height: 100,
                //id:this.id,
                crop: true
            });
        };

        img.onembedded = function() {
            this.destroy();
        };

        img.onerror = function() {
            this.destroy();
        };

        img.load(this.getSource()); 

    });
});

</script>
</body>
</html>
person Haresh Vidja    schedule 26.02.2016