我必须在java脚本中将base64编码的字符串转换为文件对象,以便我可以将该对象传递给php并通过FILE变量访问该对象。
这是我的代码:
$(document).delegate(':file', 'change', function () {
files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
filenum = $(this).attr('data');
$("form#cropmodal #filenum").val(filenum);
var oMyForm = new FormData();
for (i = 0; i < files.length; i++) {
var ext = $("#ImgId" + filenum).val().split('.').pop().toLowerCase();
output_format = ext;
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('Invalid extension');
return false;
}
var mime_type = "image/jpeg";
if (typeof output_format !== "undefined" && output_format == "png") {
mime_type = "image/png";
}
var reader = new FileReader();
reader.readAsArrayBuffer(files[i]);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
//preview.appendChild(image);
// preview commented out, I am using the canvas instead
image.onload = function () {
// have to wait till it's loaded
var cvs = document.createElement('canvas');
cvs.width = image.naturalWidth;
cvs.height = image.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(image, 0, 0);
var newImageData = cvs.toDataURL(mime_type, 50 / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
var cvs = document.createElement('canvas');
cvs.width = result_image_obj.naturalWidth;
cvs.height = result_image_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(result_image_obj, 0, 0);
var type = "image/jpeg";
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var the_file = new Blob([window.atob(data)], {type: 'image/jpeg', encoding: 'utf-8'});
oMyForm.append("media[]", the_file);
oMyForm.append("_token", "{{ csrf_token() }}");
}
};
}
});
当我提醒“the_file”时它会显示“Object Blob”,但我需要“对象文件”