Here is code which i'm using to resize and compress images in javascript this working correctly and also send one image by ajax in mysql but issue is i want to send four images in database also some extra fields. Now i want imgCompressResize function just pass image parameter and return compress and resized image so i can save as i need.
<input type="file" name="img1" id="file1" accept="image/*">
document.getElementById("file1").addEventListener("change", function (e) {
var file = imgCompressResize(e);
var data = new FormData();
data.append('file1', file);
$.ajax({
url:"page.php",
type:"POST",
data:data,
cache: false,
contentType: false,
processData: false,
success:function (data) {
alert(data);
}
});
});
function imgCompressResize(e) {
const width = 500;
const height = 600;
var file;
const fileName = e.target.files[0].name;
console.log(fileName);
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = event => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const elem = document.createElement('canvas');
elem.width = width;
elem.height = height;
const ctx = elem.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
ctx.canvas.toBlob((blob) => {
file = new File([blob], fileName, {
type: 'image/jpeg',
lastModified: Date.now()
});
return file;
// if i call here ajax() function that working for one image but i don't need
// call here ajax().
}, 'image/jpeg', .7);
},
reader.onerror = error => console.log(error);
}
}
I'm not going to rewrite this whole thing but simply give you an overview of using promises since onload
is asynchronous.
document.getElementById("file1").addEventListener("change", function(e) {
const filesArray = Array.from(this.files);
// map array of each resize promise
const filePromises = filesArray.map(imgCompressResize);
var data = new FormData();
// when all resolved append to FormData
Promise.all(filePromises).then(newFiles =>{
newFiles.forEach(f=> data.append('files[]', f)
});
// append other fields needed
//then do ajax
})
function imgCompressResize(file) {
// ^^ file instead of event
// return promise
return new Promise((resolve, reject) => {
//...
//const fileName = e.target.files[0].name;
const fileName = file.name;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = event => {
//...
img.onload = () => {
//....
const newFile = new File([blob], fileName, {...);
// resolve the promise
resolve(newFile);
});
});
});
reader.onerror = reject
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.