Ajax send & Save Base64 encoded image to server - javascript

I am passing a base64 url through jquery ajax and want to save onto the server. But the code below is giving me a empty file. I have tried writing the decoded string and createimage from string but with both variables, 0 bites have been written. When i test the value being worked on it outputs [object FileReader]......i think either i am missing a step or making a mistake some where.
Also is there a way to convert the image to a $_FILE type object? reason being id like to using a wordpress function to save the file if possible.
Php code:
function uploadimg() {
$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();
$a=0;
unset ($_POST['action']);
foreach($_POST as $basefile){
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$base64_string = $basefile;
echo $basefile;
$base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string );
$decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
$source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
$output_file = $upload_path.'myfilef'.$a.'.jpg';
$images[]=$output_file;
$a++;
$image = fopen( $output_file, 'wb' );
$bytes=fwrite( $image, $source);
echo $bytes;
fclose( $image );
}
echo json_encode($images);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
jQuery sample code
jQuery(document).on('change', '.imageup', function(event){
errors= [];
errnum=0;
numberofimages=jQuery("#selectedimages > div").length; //get number of images
if(numberofimages<10){
var id= jQuery(this).attr('id');
var length= this.files.length;
if(length>1) {// if a multiple file upload
var images = new FormData();
images.append('action', 'uploadimg'); //wordpress specific
jQuery.each(event.target.files, function(key, value ){
var size= value.size;
var extension= value.name.substring(value.name.lastIndexOf('.') + 1).toLowerCase();
var allowedExtensions = ['png', 'jpg', 'jpeg', 'gif'];
if( allowedExtensions.indexOf(extension) !== -1 ) {
if(numberofimages<10){
var file=value;
console.log(file);
var fileReader = new FileReader();
fileReader.onload = function (e) {
var img = new Image();
img.onload = function () {
var MAX_WIDTH = 100;
var MAX_HEIGHT = 100;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(this, 0, 0, width, height);
this.src = canvas.toDataURL('image/png');
} // end on load function
img.src = e.target.result;
} //end filereader function
fileReader.readAsDataURL(file);
console.log(fileReader);
images.append(key, fileReader);
numberofimages++;
} else {
errnum++;
errors[errnum]= value=' is a illegal file type';
}
}
});
//image holder finished, remove
jQuery('#'+id).remove();
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: images,
cache: false,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}//end of success function
});

ok thanks to PaulS for pointing me in the right direction....updated jQuery below........the php up top wont work with this (im cutting out the ajax even though i have included a note below to show where it goes) the array is different as i added in the filename as well as the base64 url.
jsfiddle http://jsfiddle.net/dheffernan/6Ut59/
Basically the flow is,
1.Check max files allowed
2 & then for each file check it does not exceed it.
3 Call filereader, when loaded, call resizeBase64img (thanks to the person who submitted that)
4. if on the last file to be processed -- submit FormData via Ajax
5.When file returns input div to show image & if full remove file input
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", base64).load(function() {
context.scale(width/this.width, height/this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL('image/jpg')));
});
return deferred.promise();
}
function readFile(file) {
var reader = new FileReader();
var deferred = $.Deferred();
reader.onload = function(event) {
deferred.resolve(event.target.result);
};
reader.onerror = function() {
deferred.reject(this);
};
if (/^image/.test(file.type)) {
reader.readAsDataURL(file);
} else {
reader.readAsText(file);
}
return deferred.promise();
}
jQuery(document).on('change', '.imageup', function(event){
var maximages=4;
var imagecount=jQuery("#imagesholder > div").length;
var length= this.files.length;
var images= new FormData;
var processKey=0;
var i=1;
jQuery.each(event.target.files, function(key, value){
// number of images control.
imagecount++;
if(imagecount > maximages) {
var full=true;
jQuery('.imageup').remove();
jQuery('#imageinput').html("Image Quota Full, Please delete some images if you wish to change them");
return;
} else if (imagecount == maximages) {
var full=true;
jQuery('.imageup').remove();
jQuery('#imageinput').html('<div class="image-box-full">Image Quota Full: delete images to change them</div>');
}
//call resize functions
var name=value;
$.when( readFile(value) ).done(function(value) {
resizeBase64Img(value, 300, 200).done(function(newImg){
images[processKey]=[];
images[processKey]['url']=newImg[0].src;
images[processKey]['name']=name.name;
processKey++;
if(length===processKey) {
//----------------INSERT AJAX TO RUN HERE SUBMITTING IMAGES (THE FORMDATA) E.G
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: images,
cache: false,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
}
$('#imagesholder').append('<div id="delete'+i+'">'+'<div class="image-box"><div class="box-image"><img src="'+newImg[0].src+'" style="width:50px;"/></div><div class="image-box-text">'+name.name+'</div><input type="image" src="http://testserverdavideec.mx.nf/wp-content/uploads/2014/04/success_close.png" class="deletebutton" id="delete/i'+i+'"/></div> </div>');
i++;
if(full === true) {
jQuery('.image-box-full').show();
}
});
});//end when
});//end each
jQuery(this).val('');
});//end on change

Related

Pre- resize multiple images before uploading from client side Jquery Laravel

the code is partially working, it collects images and resize them into base64 in a loop but i am not getting the images to send when i append it in form...
but when i post simple pictures by removing the resize function it sends every picture...
i don't understand that what is the issue..
heres the html:
Upload Pictures <input type="file" name="file[]" id="file" multiple/>
heres i am collecting pictures:
<script>
$(document).on('change','#file',function(){
files = this.files;
ajax_file_upload(files);
});
</script>
heres the code where i am resizing them in a loop and sending them through ajax:
note: in the resize function i am getting the resized picture in the console...
i will attach a picture of console as well...
<script>
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
var status='true';
var image = new FormData();
var match = ['image/jpeg', 'image/png', 'image/jpg'];
for(i=0; i<file_obj.length; i++) {
var fileType = file_obj[i].type;
// alert(fileType)
if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
var status='false';
}
resizeImages(file_obj[i],function(dataUrl){
image.append('file[]',dataUrl);
});
}
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{ route('resize') }}",
type: "POST",
// data: {pictures:pictures},
data:image,
cache:false,
processData: false,
contentType: false,
datatype:'html',
success: function (response) {
return true;
}
});
}
}
</script>
here the resize function i am using to resize the images and getting dataurl:
<script>
function resizeImages(file,complete) {
// read file as dataUrl
//////// 2. Read the file as a data Url
var reader = new FileReader();
// file read
reader.onload = function(e) {
// create img to store data url
////// 3 - 1 Create image object for canvas to use
var img = new Image();
img.onload = function() {
/////////// 3-2 send image object to function for manipulation
complete(resizeInCanvas(img));
};
img.src = e.target.result;
}
// read file
reader.readAsDataURL(file);
}
function resizeInCanvas(img){
///////// 3-3 manipulate image
var perferedWidth = 1200;
var ratio = perferedWidth / img.width;
var canvas = $("<canvas>")[0];
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0,canvas.width, canvas.height);
//////////4. export as dataUrl
return canvas.toDataURL('image/jpeg', 0.6);
}
</script>
this function is working perfectly...
now when i send it to the server it doesn't posts anything..
tried it many ways researched but didn't got anything..
please guide me thanks
So, I've no help but I managed to solve the issue by using tweeks....
I'm posting them so it can help someone... Thanks
here i am picking the picture and passing it to be resized and pushing them in array:
$(document).on('change','#selectfile',function(){
file_obj = this.files;
pictures_array(file_obj);
});
here the function for resizing and store it in array, i'm here restricting ajax function from running until the in array count will not equal the length of files with some validation..:
function pictures_array(file_obj){
var image_count = $('.sequence').length-1;
count = file_obj.length;
var new_count = image_count+count;
console.log(image_count,new_count,count);
if(new_count<=15){
$('.ajax-loader').css("visibility", "visible");
pictures = [];
for(i=0; i<file_obj.length; i++) {
var fileType = file_obj[i].type;
var match = ['image/jpeg', 'image/png', 'image/jpg'];
if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
var status='false';
}
resizeImages(file_obj[i],function(dataUrl){
var data = dataUrl;
pictures.push(data);
if(!--count) {
ajax(pictures);
}
});
}
}else{
$('#max_limit').html(15);
$('#limit').show();
$('html, body').animate({
scrollTop: $(".main-image").offset().top
}, 2000);
$('#selectfile').val('');
$('#selectfile1').val('');
}
}
heres the ajax call:
i am apending the base64 version of pictures using for loop in the file[]:
function ajax(pictures) {
// console.log(pictures);
var image = new FormData();
var pictures = pictures;
for (var i = 0; i < pictures.length; i++) {
image.append('file[]',pictures[i]);
}
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
// 'Content-Type': 'multipart/form-data',
},
url: "{{ route('images_private.store',$row->id) }}",
type: "POST",
data: image,
cache: false,
processData: false,
contentType: false,
datatype: 'html',
beforeSend: function(){
$('.ajax-loader').css("visibility", "visible");
},
success:function(response) {
$('#selectfile').val('');
$('#selectfile1').val('');
$('#appendhtml').html(response);
// $('#appendhtml').load('#appendhtml');
setTimeout(function() {
toastr.options = {
closeButton: true,
progressBar: true,
showMethod: 'slideDown',
timeOut: 4000
};
toastr.success('Images uploaded successfully');
}, 1300);
$("#other-image-main").sortable({
cursor: 'move',
opacity: 0.6,
update: function() {
sendOrderToServer();
}
});
},
complete: function(){
$('.ajax-loader').css("visibility", "hidden");
$('#valid_image_type').hide();
},
});
}
and then the last step in the controller:
here i am decoding the base64 to jpeg file and storing it into the server:
if(!File::isDirectory($path)){
File::makeDirectory($path, 0777, true, true);
}
if($request->has('file')){
foreach ($request->file as $image){
$position++;
list($type, $image) = explode(';', $image);
list(, $image) = explode(',', $image);
$image = base64_decode($image);
$source_img = imagecreatefromstring($image);
$filename= uniqid() . '.jpg';
$filepath = $path.$filename ;
$imageSave = imagejpeg($source_img, $filepath);
ImagesPrivate::create([
'user_id'=>$id,
'owner_id'=>$auth,
'name'=>$filename,
'position'=>$position,
'position_change'=>$position,
'delete' => 'pending',
]);
}
}
So, in the end 4.8MB picture is now weigh 316KB thats a success,,,
i am posting this because i haven't found anything like that and it took me time to do this,,, may be i haven't researched properly but this is how i manage to upload multiple images pre-resized on client side without any trigger button...
cuts uploading time to 90%...
Hope that helps someone Thanks
Regards

crop image with jcrop I get a black image when decode it in base64

I used a lot time, trying to get a successful decode image in base64, but I get a black image. I don't know what is wrong.
I am using jcrop
I need yo two thing.
Get a successful image when decode it base64 and I can rotate image before to crop. Appreciate your help or recommendations.
I am using this example is not mine in jisfidle
var cropCoords,
file,
uploadSize = 360,
previewSize = 500;
$("input[type=file]").on("change", function(){
file = this.files[0];
readFile(file, {
width: previewSize,
height: previewSize
}).done(function(imgDataUrl, origImage) {
$("input, img, button").toggle();
initJCrop(imgDataUrl);
}).fail(function(msg) {
alert(msg);
});
});
$("button[type=submit]").on("click", function(){
$(this).text("Uploading...").prop("disabled", true);
readFile(file, {
width: uploadSize,
height: uploadSize,
crop: cropCoords
}).done(function(imgDataURI) {
var data = new FormData();
var blobFile = dataURItoBlob(imgDataURI);
data.append('file', blobFile);
$.ajax({
url: "/upload",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function() {
alert("Yay!");
},
error: function(xhr) {
alert("Well, obviously we can't upload the file here."+
"This is what the data looks like: " +
imgDataURI.substr(0,128)+"...");
console.log(imgDataURI);
}
});
});
});
/*****************************
show local image and init JCrop
*****************************/
var initJCrop = function(imgDataUrl){
var img = $("img.crop").attr("src", imgDataUrl);
var storeCoords = function(c) {
cropCoords = c;
};
var w = img.width();
var h = img.height();
var s = uploadSize;
img.Jcrop({
onChange: storeCoords,
onSelect: storeCoords,
aspectRatio: 1,
setSelect: [(w - s) / 2, (h - s) / 2, (w - s) / 2 + s, (h - s) / 2 + s]
});
};
/*****************************
Read the File Object
*****************************/
var readFile = function(file, options) {
var dfd = new $.Deferred();
var allowedTypes = ["image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/bmp"];
if ($.inArray(file.type, allowedTypes) !== -1) {
//define FileReader object
var reader = new FileReader();
var that = this;
//init reader onload event handlers
reader.onload = function(e) {
var image = $('<img/>')
.load(function() {
//when image is fully loaded
var newimageurl = getCanvasImage(this, options);
dfd.resolve(newimageurl, this);
})
.attr('src', e.target.result);
};
reader.onerror = function(e) {
dfd.reject("Couldn't read file " + file.name);
};
//begin reader read operation
reader.readAsDataURL(file);
} else {
//some message for wrong file format
dfd.reject("Selected file format (" + file.type + ") not supported!");
}
return dfd.promise();
};
/*****************************
Get New Canvas Image URL
*****************************/
var getCanvasImage = function(image, options) {
//define canvas
var canvas = document.createElement("canvas"),
ratio = {
x: 1,
y: 1
};
if (options) {
if (image.height > image.width) {
ratio.x = image.width / image.height;
} else {
ratio.y = image.height / image.width;
}
}
canvas.height = options.crop ? Math.min(image.height, options.height) : Math.min(image.height, Math.floor(options.height * ratio.y));
canvas.width = options.crop ? Math.min(image.height, options.width) : Math.min(image.width, Math.floor(options.width * ratio.x));
var ctx = canvas.getContext("2d");
if (options.crop) {
//get resized width and height
var c = options.crop;
var f = image.width / options.previewWidth;
var t = function(a) {
return Math.round(a * f);
};
ctx.drawImage(image, t(c.x), t(c.y), t(c.w), t(c.h), 0, 0, canvas.width, canvas.height);
} else {
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}
//convert canvas to jpeg url
return canvas.toDataURL("image/jpeg");
};
/*****************************
convert dataURI to blob
*****************************/
var dataURItoBlob = function(dataURI) {
var blob = window.Blob || window.WebKitBlob || window.MozBlob;
//skip if browser doesn't support Blob object
if (typeof blob === "undefined") {
alert("Oops! There are some problems with your browser! <br/>New image produced from canvas can\'t be upload to the server...");
return dataURI;
}
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString;
if (dataURI.split(',')[0].indexOf("base64") >= 0) {
byteString = atob(dataURI.split(',')[1]);
} else {
byteString = unescape(dataURI.split(',')[1]);
}
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new blob([ab], {
type: mimeString
});
};
html
<input type="file" />
<img class="crop" style="display:none" />
<button type="submit" style="display:none">Upload</button>
I get a black image when decode it in base64
Example image
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCABLAEsDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8qqKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/2Q==

The compatibility issue about new File([Blob],filename) [duplicate]

Ok I am stumped, I have been able to successfully upload resized image/blob to server folder. The problem is that the image/blob upload is always called blob. Is there a way to change name on client side or should i do it on server PHP side?.
And if so can you please give me an example here is the 2 scripts I am using to communicate with
client side Resize
<script>
function handleFiles(){
var dataurl = null;
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
dataurl = canvas.toDataURL("image/jpeg",.2);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: ""});
var filename = getFileName()
// Post the data
var fd = new FormData();
fd.append("image",files);
$.ajax({
url: 'http:///www.i-audit-jci.com/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
Server PHP
<?php
$upload_image = $_FILES["image"][ "name" ];
$a = ('" alt="" />');
$folder = "images/";
move_uploaded_file($_FILES["image"]["tmp_name"], "$folder".$_FILES["image"]["name"]);;
$file = 'images/'.$_FILES["image"]["name"];
$uploadimage = $folder.$_FILES["image"]["name"];
$newname = $_FILES["image"]["name"];
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$a = ('" alt="" />');
$image = $_FILES['image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('mysql***','***','***','***') or die('Unable To connect');
$sql = ("INSERT into links (hyper_links) VALUES('<img src=\"\https://www.i-audit-jci.com/images/".$_FILES['image']['name']."$a')");
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Successfullly UPloaded';
}else{
$msg = 'Could not upload';
}
mysqli_close($con);
}
?>
<?php
echo $msg;
?>
You can set the name property of a File object passed to FormData at third parameter of FormData.append() function
var blob = new Blob([123], {
type: "text/plain"
});
var data = new FormData();
// set `blob` name to `"file.txt"`
data.append("file", blob, "file.txt");
console.log(data.get("file"), data.get("file").name);

Rename BLOB form.append

Ok I am stumped, I have been able to successfully upload resized image/blob to server folder. The problem is that the image/blob upload is always called blob. Is there a way to change name on client side or should i do it on server PHP side?.
And if so can you please give me an example here is the 2 scripts I am using to communicate with
client side Resize
<script>
function handleFiles(){
var dataurl = null;
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
dataurl = canvas.toDataURL("image/jpeg",.2);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: ""});
var filename = getFileName()
// Post the data
var fd = new FormData();
fd.append("image",files);
$.ajax({
url: 'http:///www.i-audit-jci.com/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
Server PHP
<?php
$upload_image = $_FILES["image"][ "name" ];
$a = ('" alt="" />');
$folder = "images/";
move_uploaded_file($_FILES["image"]["tmp_name"], "$folder".$_FILES["image"]["name"]);;
$file = 'images/'.$_FILES["image"]["name"];
$uploadimage = $folder.$_FILES["image"]["name"];
$newname = $_FILES["image"]["name"];
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$a = ('" alt="" />');
$image = $_FILES['image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('mysql***','***','***','***') or die('Unable To connect');
$sql = ("INSERT into links (hyper_links) VALUES('<img src=\"\https://www.i-audit-jci.com/images/".$_FILES['image']['name']."$a')");
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Successfullly UPloaded';
}else{
$msg = 'Could not upload';
}
mysqli_close($con);
}
?>
<?php
echo $msg;
?>
You can set the name property of a File object passed to FormData at third parameter of FormData.append() function
var blob = new Blob([123], {
type: "text/plain"
});
var data = new FormData();
// set `blob` name to `"file.txt"`
data.append("file", blob, "file.txt");
console.log(data.get("file"), data.get("file").name);

Listen for the statement until it's true

I'm looking for the solution to my problem with image upload. I have one script that is kind of compressing my files with Javascript. Then it creates an Array with results in base64 which I want to add to my page as an <input type="hidden">. I have just one problem. It takes a bit to compress these images and .change() event on file input is not enough. Because it begins before the compression is done.
I was thinking about adding something like event listener for the statement, something like:
if(result_base64.length != input.files.length){
listen
} else {
do the function
}
Is it possible to achieve that without setting the interval function?
The compression script:
var result_base64 = [];
var images = document.getElementById('images');
var max_width = images.getAttribute('data-maxwidth');
var max_height = images.getAttribute('data-maxheight');
images.onchange = function(){
if ( !( window.File && window.FileReader && window.FileList && window.Blob ) ) {
alert('The File APIs are not fully supported in this browser.');
return false;
}
readfiles(images.files);
}
function readfiles(files) {
for (var i = 0; i < files.length; i++) {
processfile(files[i]);
}
images.value = "";
}
function processfile(file) {
if( !( /image/i ).test( file.type ) ){
alert( "File "+ file.name +" is not an image." );
return false;
}
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
var image = new Image();
image.src = blobURL;
image.onload = function() {
result_base64.push(resizeMe(image));
}
};
}
function resizeMe(img) {
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if (width > height) {
if (width > max_width) {
height = Math.round(height *= max_width / width);
width = max_width;
}
} else {
if (height > max_height) {
width = Math.round(width *= max_height / height);
height = max_height;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL("image/jpeg",0.7);
}
Then it creates an Array with results in base64
In processFile() you can fire an event like
function processfile(file) {
if( !( /image/i ).test( file.type ) ){
alert( "File "+ file.name +" is not an image." );
return false;
}
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
var image = new Image();
image.src = blobURL;
image.onload = function() {
result_base64.push(resizeMe(image));
$(window).trigger('filesCompressed', result_base64); // This is the addition
}
};
}
Where you need these files, you can listen for this event like
$(window).on('filesCompressed', function(e, files) {
// Do something with files
})
Catch: The listening code must execute before the event is triggered.

Categories

Resources