简体   繁体   English

Javascript:通过 xhr 将两个 base64 编码图像数组发送到 php

[英]Javascript: Sends two arrays of base64 encoded images to php via xhr

Hello everyone I'm here again.大家好,我又来了。 I'm trying to write a code that's able to resize all images before they're uploaded to the server.我正在尝试编写一个代码,该代码能够在将所有图像上传到服务器之前调整它们的大小。 Once these images are in server-side, I need to know which array they belong to treat each one differently.一旦这些图像在服务器端,我需要知道它们属于哪个数组以不同的方式对待每一个。 For this purpose I'm using two arrays taht's get files from two inputs as shown in the code below:为此,我使用两个数组从两个输入获取文件,如下面的代码所示:

HTML HTML

<form method="post">
<input type="file" name="one[]" id="one" accept="image/jpeg, image/jpg" size="6" multiple/>
<input type="file" name="two[]" id="two" accept="image/jpeg, image/jpg" size="6" multiple/>
<button type="submit" id="submitButton">Submit</button>
</form>

JAVASCRIPT爪哇脚本

var imgMaxWidth   = 1014; //Max width to resized image
var imgMaxHeight  = 1350; //Max height to resized images
var arrayOne = [];
var arrayTwo = [];
var arrayTest = ['zero', 'one', 'two'];

$(function() {
    var submitButton = $("#submitButton")
    /**
     * Resizes all images before upload
     * @param  {object?} input that contain images files
     * @param  {array} arrayIndex decides which array to push
     */
    var resizeBeforeUpload = function(input, arrayIndex) {
      // Checks has inputed files
      if (input.files) {
        // count files
        var filesAmount = input.files.length;
        // loop through files
        for (i = 0; i < filesAmount; i++) {
          // creates file reader object
          var reader = new FileReader();
          // awaits load end
          reader.onloadend = function(event) {
            var tempImg = new Image();
            tempImg.src = event.target.result;
            // execute when images load
            tempImg.onload = function() {
              // Assigns the variables according to previously defined limits
              var MAX_WIDTH = imgMaxWidth;    //imgMaxWidth  = 1014;
              var MAX_HEIGHT = imgMaxHeight; //imgMaxHeight  = 1350;
              var tempW = tempImg.width;
              var tempH = tempImg.height;
              // Handles de sizes correction
              if (tempW > tempH) // is width greater than height?
              { 
                if (tempW > MAX_WIDTH) { // is image.width greater than MAX_WIDTH variable?
                  // Image.height equals Image.height * MAX_WIDTH divided by image.width
                  tempH *= MAX_WIDTH / tempW;
                  tempW = MAX_WIDTH;
                }
              } else {
                if (tempH > MAX_HEIGHT) {
                  tempW *= MAX_HEIGHT / tempH;
                  tempH = MAX_HEIGHT;
                }
              }
              // Creates a canvas element
              var canvas = document.createElement('canvas');
              // Assigns width and height to canvas
              canvas.width = tempW;
              canvas.height = tempH;
              // Returns a bidimensional drawing context on canvas
              var ctx = canvas.getContext("2d");
              // Draw the image
              ctx.drawImage(this, 0, 0, tempW, tempH);
              /* Returns a base64 from the canvas, 
              [0.6] is a image quality indicator -> [from 0.1=low, to 1.0=high]*/
              var dataURL = canvas.toDataURL("image/jpeg", 0.6);
              // *** here starts the mess ***
              // I added the index checking to be able to separate arrays
              if (arrayIndex == 1) {
                // push this array
                arrayOne.push(dataURL);
              } else if (arrayIndex == 2) {
                // push this array
               arrayTwo.push(dataURL);
              }
            }
          }
          reader.readAsDataURL(input.files[i]);
        }
      }
    };
    // On click form submit button
    submitButton.unbind().click(function(e){
       $(this).prop("disabled", true);
      // prevent default submiting form
      e.preventDefault();
      // run resizeBeforeUpload(input, index=1);
      resizeBeforeUpload(document.getElementById('one'), 1)
      console.log(arrayOne);
      // run resizeBeforeUpload(input, index=2);
      resizeBeforeUpload(document.getElementById('two'), 2)
      console.log(arrayTwo);
      console.log(arrayTest);

      
    });
  });

But when I send the form by clicking its button, the data is sent incompletely.但是当我通过单击其按钮发送表单时,数据发送不完整。 Sometimes I get all arrays with all images, but sometimes only some images are being uploaded.有时我会得到包含所有图像的所有数组,但有时只会上传一些图像。 I believe this is happening because the form is being submitted before the entire array is filled.我相信这是因为在填充整个数组之前提交了表单。 Could you help me resolve this issue?你能帮我解决这个问题吗? I need to get the list of images from each of the inputs, then I need each of these images reduced, then I need them to be uploaded to the server in base64 format.我需要从每个输入中获取图像列表,然后我需要缩小这些图像中的每一个,然后我需要将它们以 base64 格式上传到服务器。 Something like this:像这样的东西:

data = 'firstArray='+arrayOne+'&secondArray='+arrayTwo;
xhr.send(data);

With each of the arrays separate I'll be able to put each of them in different tables in the database:将每个数组分开后,我将能够将每个数组放在数据库中的不同表中:

[...]
$firstArray = $_POST[firstArray][i];
$secondArray = $_POST[secondArray][i];
[...]

Here's a fiddle example: link这是一个小提琴示例:链接

Javascript doesn't wait for asynchronous functions. Javascript 不等待异步函数。 When resizeBeforeUpload is finished, reader.onloadend will not be executed yet.resizeBeforeUpload完成后, reader.onloadend还不会被执行。 You should make resizeBeforeUpload function to return a promise .你应该让resizeBeforeUpload函数返回一个promise

In the submit function you should wait both to finish with Promise.all .在提交函数中,您应该等待Promise.all完成。

Your functions should look like below.您的函数应如下所示。

var imgMaxWidth   = 1014; //Max width to resized image
var imgMaxHeight  = 1350; //Max height to resized images
var arrayOne = [];
var arrayTwo = [];
var arrayTest = ['zero', 'one', 'two'];
$(function() {
    var submitButton = $("#submitButton")
    /**
     * Resizes all images before upload
     * @param  {object?} input thats contain images files
     * @param  {array} arrayIndex decides which array to push
     */
    var resizeBeforeUpload = function(file) {
        return new Promise(resolve => {
      
            // creates file reader object
            var reader = new FileReader();
            // awaits load end
            reader.onloadend = function(event) {
              var tempImg = new Image();
              tempImg.src = event.target.result;
              // execute when images load
              tempImg.onload = function() {
                // Assigns the variables according to previously defined limits
                var MAX_WIDTH = imgMaxWidth;    //imgMaxWidth  = 1014;
                var MAX_HEIGHT = imgMaxHeight; //imgMaxHeight  = 1350;
                var tempW = tempImg.width;
                var tempH = tempImg.height;
                // Handles de sizes correction
                if (tempW > tempH) // is width greater than height?
                { 
                  if (tempW > MAX_WIDTH) { // is image.width greater than MAX_WIDTH variable?
                    // Image.height equals Image.height * MAX_WIDTH divided by image.width
                    tempH *= MAX_WIDTH / tempW;
                    tempW = MAX_WIDTH;
                  }
                } else {
                  if (tempH > MAX_HEIGHT) {
                    tempW *= MAX_HEIGHT / tempH;
                    tempH = MAX_HEIGHT;
                  }
                }
                // Creates a canvas element
                var canvas = document.createElement('canvas');
                // Assigns width and height to canvas
                canvas.width = tempW;
                canvas.height = tempH;
                // Returns a bidimensional drawing context on canvas
                var ctx = canvas.getContext("2d");
                // Draw the image
                ctx.drawImage(this, 0, 0, tempW, tempH);
                /* Returns a base64 from the canvas, 
                [0.6] is a image quality indicator -> [from 0.1=low, to 1.0=high]*/
                var dataURL = canvas.toDataURL("image/jpeg", 0.6);
                resolve(dataURL);
              }
            }
            reader.readAsDataURL(file);
      });
    };
    
    var getFiles = (inputElement) => {
    
        const promiseArray = Array.from(inputElement.files).map(file => resizeBeforeUpload(file));
    
        return Promise.all(promiseArray);
    };
    
    // On click form submit button
    submitButton.unbind().click(function(e){
        $(this).prop("disabled", true);
      // prevent default submiting form
      e.preventDefault();
      Promise.all([
        getFiles(document.getElementById('one')),
        getFiles(document.getElementById('two')),
        ]).then(([oneResults, twoResults]) => {
        console.log(oneResults);
        console.log(twoResults);
      })
    });
});

Fiddle Link小提琴链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM