如何使用浏览器图像压缩脚本与AJAX帖子



我希望使用Ajax将图像上传到我的服务器。但我必须在上传之前压缩它,因为图像大小会很大。我发现了一个名为浏览器图像压缩的脚本。我已经在AJAX中尝试这个脚本大约5个小时了,但我做不到。Ajax仍然发送原始大小。我对Javascript还很陌生。

脚本https://github.com/Donaldcwl/browser-image-compression

JSfiddlehttps://jsfiddle.net/rd8f6vqu/2/

我用sweetalert2打开图像加载屏幕。

myfunction

function addImage (image_type, game) {
var confirmText = 'Submit';
var cancelText = 'Cancel';
var main_title = 'Title';
var img_icon = '<span class="material-symbols-outlined gp-imageupload-titleicon">swords</span>';
Swal.fire({
customClass: {
container: 'gp-imageupload-body',
popup: 'swall-custom-backgroundcolor swall-custom-border',
title: 'swall-custom-title',
htmlContainer: 'swall-custom-textcolor',
icon: 'swall-custom-icon',
validationMessage: 'swall-custom-validatormsg',
},
title: main_title,
iconHtml: img_icon,
html:
'<div class="gp-imageupload-box">' +
'<form action="#" id="gp-imageupload-sendForm">' +
'<div id="gp-imageupload-drop-area">' +
'<label for="gp-imageupload-fileElem">' +
'<input type="file" name="uploaded_image" id="gp-imageupload-fileElem" onchange="handleFiles(this.files)" />' +
'<div class="uploadIcon">' +
'<i class="fa fa-cloud-upload fa-4x" aria-hidden="true"></i>' +
'<p>Paste Image <span class="or">or</span> Drag & Drop <span class="or">or</span> Click & Select</p>' +
'<p class="last">Only jpeg, jpg and png</p>' +
'</div>' +
'<div id="gp-imageupload-gallery"></div>' +
'</label>' +
'<div class="gp-imageupload-control-panel">' +
'<div class="item">' +
'<div id="delete-image"><span class="material-symbols-outlined">delete_forever</span></div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="progress-wrapper">' +
'<div class="progress-info">' +
'<div class="progress-percentage">' +
'<span class="text-sm font-weight-bold" id="gp-imageupload-progressbar-span">0%</span>' +
'</div>' +
'</div>' +
'<div class="progress">' +
'<div class="progress-bar bg-primary" id="gp-imageupload-progressbar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
'</div>' +
'</div>' +
'<div id="gp-imageupload-details_img">' +
'<div class="list">' +
'<div class="item">' +
'<div class="attr">Name</div>' +
'<div class="data" id="nameImage">No Data</div>' +
'</div>' +
'<div class="item">' +
'<div class="attr">Size</div>' +
'<div class="data" id="sizeImage">No Data</div>' +
'</div>' +
'<div class="item">' +
'<div class="attr">Type</div>' +
'<div class="data" id="typeImage">No Data</div>' +
'</div>' +
'</div>' +
'</div>' +
'</form>' +
'</div>' +
'<div id="gp-imageupload-container-image"></div>',
showCloseButton: false,
showCancelButton: true, 
focusConfirm: false,
confirmButtonText: confirmText,
cancelButtonText: cancelText,
showLoaderOnConfirm: true,
preConfirm: function() {
var ext = $('#gp-imageupload-fileElem').val().split('.').pop().toLowerCase();
console.log(ext);
if($.inArray(ext, ["jpg","jpeg","png"]) == -1) {
Swal.showValidationMessage(
`Error`
)
}

},
}).then((result) => {
if(result.value){
var file_input = $('#gp-imageupload-fileElem');
var progress_bar = $('#gp-imageupload-progressbar');
var progress_percent = $('#gp-imageupload-progressbar-span');
var original_file = $('#gp-imageupload-fileElem')[0].files[0];
const options = {
maxWidthOrHeight: 1000,
useWebWorker: true
}
imageCompression(original_file, options)
.then(function (compressedFile) {+
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});

var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
$.ajax({
url: 'editimage.php',
type: 'POST',
data: filedata,
dataType: "json",
cache:false,
contentType: false,
processData: false,
beforeSend: function() {
var percentVal = '0%';
var percentVal2 = '0';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
progress_bar.attr("aria-valuenow", percentComplete);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
complete: function(xhr) {
var percentVal = '100%';
var percentVal2 = '100';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
success: function(result){
if (result.status == true) {

}
else {

}                 
}
});
}else {
window.removeEventListener('paste', pasteImage);
}
});
window.nodata_text = 'No Data';
$.getScript( "/assets/js/imageuploader.js?ver=111" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
};

控制台日志

xxxx Uncaught (in promise) ReferenceError: compressedFile is not defined
at xxxx
compressedFile instanceof Blob true
xxxx compressedFile size 0.12560653686523438 MB

图像上传器.js

// ************************ Drag and drop ***************** //
//# sourceURL=/assets/js/imageuploader.js?ver=111
var dropArea = document.getElementById("gp-imageupload-drop-area")
var fileElem = document.getElementById('gp-imageupload-fileElem');
var gallery = document.getElementById('gp-imageupload-gallery');
// Prevent default drag behaviors
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
dropArea.addEventListener('DOMNodeInserted',function () {
$('.uploadIcon').css('display','none');
if($('#gp-imageupload-gallery').children().length > 1) {
$('#gp-imageupload-gallery').children().first().remove();
}
});
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
function handleDrop(e) {
e.preventDefault();
var fileInput = document.getElementById("gp-imageupload-fileElem");
fileInput.files = e.dataTransfer.files;
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
function handleFiles(files) {
files = [...files];
files.forEach(previewFile);
}
function previewFile(file) {
var reader = new FileReader();
reader.onloadend = function() {
dropArea.style.height = '100%';
let img = document.createElement('img');
img.src = reader.result
gallery.appendChild(img);
setDataForImage(file);

}
reader.readAsDataURL(file);
}

//********************paste********************//
//var input = document.querySelector("#gp-imageupload-text");
var pasteImage = function(event){
const fileInput = document.getElementById("gp-imageupload-fileElem");
fileInput.files = event.clipboardData.files;
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();

reader.onload = function(event){
let img = document.createElement('img')
img.src = event.target.result
document.getElementById('gp-imageupload-gallery').appendChild(img);
setDataForImage(blob);
};
reader.readAsDataURL(blob);

}
}
}
window.addEventListener("paste", pasteImage);

function setDataForImage(file)
{
var nameImage = $('#nameImage');
var sizeImage = $('#sizeImage');
var typeImage = $('#typeImage');
//var timemodifiImage = $('#timemodifiImage');
//var datemodifiImage = $('#datemodifiImage');
var filesizetoMB = file.size / 1024 / 1024;
console.log('file',file);
nameImage.text(file.name);
sizeImage.text(filesizetoMB.toFixed(2)+' MB');
typeImage.text(file.type);
//timemodifiImage.text(file.lastModified);
//datemodifiImage.text(file.lastModifiedDate);
}
var deleteImageBtn = $('#delete-image');
deleteImageBtn.click(function(){
var image = $('#gp-imageupload-gallery').children().first().remove();
var nameImage = $('#nameImage');
var sizeImage = $('#sizeImage');
var typeImage = $('#typeImage');
$('.uploadIcon').css('display','flex');
fileElem.value = "";
nameImage.text(nodata_text);
sizeImage.text(nodata_text);
typeImage.text(nodata_text);
});

好吧,我想明白了。

xxxx Uncaught (in promise) ReferenceError: compressedFile is not defined

发生这种情况是因为Promise((

Javascript中的Promise表示已经开始的操作,但是一个将在以后完成的。

当我查看Chrome断点时,以下代码

filedata.append('file', compressedFile);

在之前发送

imageCompression(original_file, options)
.then(function (compressedFile) {+
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});

这就是它返回undefined的原因。为了解决这个问题,我在函数中包含了$.ajax代码。像这样,

function ajaxpost (dataForm) {
$.ajax({
// some ajax codes
});
}

然后我在promise中调用这个函数,一切都解决了。

imageCompression(original_file, options)
.then(function (compressedFile) {
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeM
var file_Type = compressedFile.type.split('/').pop().toLowerCase();
var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
filedata.append('file_type', file_Type);
ajaxpost(filedata);
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});

此处为最终代码;

imageCompression(original_file, options)
.then(function (compressedFile) {
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeM
var file_Type = compressedFile.type.split('/').pop().toLowerCase(); // compressedFile.type = image/png. With this code I only get the last "png".
var filedata = new FormData();
filedata.append('game', game);
filedata.append('data', image_type);
filedata.append('input_val', "image");
filedata.append('file', compressedFile);
filedata.append('file_type', file_Type);
ajaxpost(filedata);
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});

function ajaxpost (dataForm) {
$.ajax({
url: 'editgameprofile.php',
type: 'POST',
data: dataForm,
dataType: "json",
cache:false,
contentType: false,
processData: false,
beforeSend: function() {
var percentVal = '0%';
var percentVal2 = '0';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
progress_bar.attr("aria-valuenow", percentComplete);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
complete: function(xhr) {
var percentVal = '100%';
var percentVal2 = '100';
progress_bar.attr("aria-valuenow", percentVal2);
progress_bar.css("width", percentVal);
progress_percent.text(percentVal);
},
success: function(result){
if (result.status == true) {

}
else {

}                   
}
});
}

相关内容

  • 没有找到相关文章

最新更新