[英]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.