Ajax-enabled pre-resize feature for efficient multiple file uploads

I'm currently facing an issue with a function that involves pre-resizing and ajax file uploading. I have a FOR loop which calls this function, depending on the length of the file input size. The strange thing is, sometimes when I call it multiple times, the function ends up uploading duplicate images. My theory is that the current function call starts before the previous one has finished, potentially causing it to use the same canvas. Can anyone suggest a fix for this problem? Any help would be greatly appreciated!

Below is the relevant code snippet:

...

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);
}

Answer №1

If you want to upload multiple files with resizing on the client side, you can utilize the plUpload plugin. Here is an example code snippet that demonstrates how it can be done:

<!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>Custom Uploader 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 Uploader Example</h1>

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

<div id="filelist">Your browser doesn't support Flash, Silverlight, or HTML5.</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 disabled");
                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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive div with dynamically generated click event

I need to add an onclick event to a button that is being generated dynamically via ajax. How can I achieve this? This is the code responsible for generating the content. When we click on an item, I want a popup window to appear. function retrieveTableDat ...

Ajax script success function in jQuery

This situation has been frustrating me for the past few days. I'm really in need of assistance. There are 2 files, namely index.php and test.php, and I will provide simplified versions below. index.php <div id="div-greetings"></div> < ...

AJAX for efficient storage of various input fields

Currently, I am working on saving input field values dynamically using AJAX in my Laravel framework applications. The issue lies in the fact that all input field names are identical in each table row, causing only the value from the first row to be submitt ...

Building interactive form elements using jQuery Mobile

Hello! I have a question that I couldn't find an answer to through search... I'm currently exploring jQuery Mobile and trying to dynamically add radio buttons to a <fieldset> container within a page. You can view my code in this fiddle: ht ...

Learn how to dynamically clear and update source data in jQuery autocomplete for enhanced functionality

Here is a snippet of my jQuery code. In this code, 'year' refers to the form input tag ID, and 'years' is an array variable containing all the year values. I have set this array as the source for autocomplete, which works fine. However, ...

Pressing anywhere will close the MagnificPopup ajax box

Every time I attempt to fill out the login form (which appears as a magnificent pop-up AJAX box), it unexpectedly closes with just one click. main.html $(document).ready(function() { $('.ajax-popup-link').magnificPopup({ ...

Having an issue with the 'scroll' event not being disabled in jQuery

Currently, we are encountering an issue with the implementation of a simple hiding menu when scrolling and showing it back once the user stops scrolling. The method .on('scroll') works as expected, but .off('scroll') is not functioning ...

Unexpected issue with Ajax call execution

I am facing an issue with my ajax call as it is not behaving as expected. The browser is throwing an error message saying "jquery-1.10.2.js:8157 Uncaught TypeError: Cannot read property 'FileGuid' of undefined". I have set breakpoints in my CS fi ...

When attempting to change the text in the textarea by selecting a different option from the dropdown list, the text is not updating

I am facing an issue with three multi-select dropdown lists. When a user selects options from these lists and then presses the submit button, the selected text should display in a textarea. However, if the user manually changes some text in the textarea ...

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

Utilizing jQuery to make AJAX requests to multiple URLs

I am experiencing some difficulty running an Ajax call due to complications in locating the script.php file within my folder. This issue is a result of the RewriteRule in my htaccess file, which changes the formatting of URLs from "domain.com/index.php?bla ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

Submitting a form using jquery

I am working on a project that involves using a jquery fancyzoom box. Within this box, there is a contact form that should send an email upon submission. However, I am encountering issues with calling the form submit function due to the fancyzoom feature. ...

Transferring a JavaScript variable to PHP using Ajax within the same webpage

Check out my HTML and JavaScript code: <form id="form" action="javascript:void(0)"> <input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font- ...

Banner advertisement on a webpage

Currently, I am working on a website project for clients who are interested in having background ads displayed throughout the entire site. In terms of coding this feature with CSS, it is relatively straightforward: body { background-image: url('a ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

Having trouble sending data to an API through jQuery: the function is not functioning properly

Currently, I am in the process of developing an HTML form that allows users to input values into text fields and submit them to an external API called ThingSpeak. This API then uses the received values to generate a plot displayed within an iframe. Althoug ...

Displaying Indonesian rupiah prices in jQuery using JSON data format

Here is some JSON data: {"grand_total":"1.200.000"} I need to display this JSON in $("jumlah").val(data.grand_total); Any suggestions on how to solve this? Thanks! ...