繁体   English   中英

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

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

大家好,我又来了。 我正在尝试编写一个代码,该代码能够在将所有图像上传到服务器之前调整它们的大小。 一旦这些图像在服务器端,我需要知道它们属于哪个数组以不同的方式对待每一个。 为此,我使用两个数组从两个输入获取文件,如下面的代码所示:

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>

爪哇脚本

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

      
    });
  });

但是当我通过单击其按钮发送表单时,数据发送不完整。 有时我会得到包含所有图像的所有数组,但有时只会上传一些图像。 我相信这是因为在填充整个数组之前提交了表单。 你能帮我解决这个问题吗? 我需要从每个输入中获取图像列表,然后我需要缩小这些图像中的每一个,然后我需要将它们以 base64 格式上传到服务器。 像这样的东西:

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

将每个数组分开后,我将能够将每个数组放在数据库中的不同表中:

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

这是一个小提琴示例:链接

Javascript 不等待异步函数。 resizeBeforeUpload完成后, reader.onloadend还不会被执行。 你应该让resizeBeforeUpload函数返回一个promise

在提交函数中,您应该等待Promise.all完成。

您的函数应如下所示。

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

小提琴链接

暂无
暂无

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

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