Upload multiple images to server in ajax request - javascript

I have a web application that create post with 15 images maximum and other data, I am using AJAX request to send all data with images in one request but I got this error:
An error occurred during the serialization or de-serialization process with JSON JavaScriptSerializer. The length of the string exceeds the value set in the MaxJsonLength property.
I am trying to compress the images before uploading but same problem still.
That's the JS code:
function readURL(input) {
var files = input.files;
for (var index = 0; index < files.length; index++) {
var mainImage = "";
if (files && files[index]) {
var reader = new FileReader();
reader.onload = function (e) {
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
if ($(".imgUpload li").length <= 15) {
imgElement.onload = function (e) {
const canvas = document.createElement("canvas");
const MAX_WIDTH = 960;
const scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
// you can send srcEncoded to the server
$(".imgUpload").append('<li class="d-inline-block vTop position-relative mr-3 ' + mainImage + '"><a class="removeImg center w3-text-white fullRadius osRedBg position-absolute" data-ghost="removeImg" href="javascript:;"><svg viewBox="0 0 32 32" width="20" height="20" class="d-inline-block vMiddle" data-name="IconClose"><path fill="#ffffff" stroke="#fff" stroke-width="1" d="M25.333 8.547l-1.88-1.88-7.453 7.453-7.453-7.453-1.88 1.88 7.453 7.453-7.453 7.453 1.88 1.88 7.453-7.453 7.453 7.453 1.88-1.88-7.453-7.453z"></path></svg></a><img class="ad-img" alt="" src="' + srcEncoded + '"></li>');
if ($('.imgUpload li.mainImage').length == 0) {
$('.imgUpload li:nth-child(2)').addClass("mainImage");
}
if ($(".imgUpload li").length > 2) {
$(".imgValMsg").text("#Messages.ClickToDetectMainImage");
}
};
}
else {
$('.modalCountImgs').modal('show');
}
if ($('.imgUpload li.mainImage').length == 0) {
$('.imgUpload li:nth-child(2)').addClass("mainImage");
}
if ($(".imgUpload li").length > 2) {
$(".imgValMsg").text("#Messages.ClickToDetectMainImage");
}
}
reader.readAsDataURL(files[index]); // convert to base64 string
}
}
}
$("#inputAddImage").change(function () {
var input = this;
var files = this.files;
var validFiles = true;
for (var index = 0; index < files.length; index++) {
var extLogo = files[index].name.split('.').pop().toLowerCase();
if ($.inArray(extLogo, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
validFiles = false;
break;
}
}
if (validFiles) {
readURL(input);
$("#Imgs-error2").removeClass("d-block").addClass("d-none");
}
else {
$("#Imgs-error2").removeClass("d-none").addClass("d-block");
}
$("#Imgs-error").removeClass("d-block").addClass("d-none");
});
and AJAX request:
//Images
var lstImgs = [];
var ImgElements = $(".imgUpload img");
ImgElements.each(function () {
var obj = {
ImageData: $(this).attr("src")
}
lstImgs.push(obj);
});
var productModel = {
CategoryThirdId: $("#CategoryThirdId").val(),
ProductTitle: $("#ProductTitle").val(),
ProductDescription: $("#ProductDescription").val(),
Price: $("#Price").val(),
Images:lstImgs
};
var data = {
model:productModel
};
$.ajax({
method: "post",
url: '#Url.Action("CreateAdvertise", "Advertise")',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (res) {
if (res != null) {
if (res == "ErrorCatalogName") {
$(".danger-product-name").show();
}
}
else {
$(".danger-product-name").hide();
}
$('#overlay').fadeOut();
},
error: function (res) {
$('#overlay').fadeOut();
}
});
At the end my goal is to upload 15 images and other data from client to server witch I use ASP .NET MVC
and the images to be compressed until the user upload an image with 20 MB.

You can't post files as string. Use something like this:
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: '/Example/SendData',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});

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

How to save gif images to imgur api using ajax

I am trying to upload the gif images on imgur server using ajax. code is working fine for png and jpg. but when I am trying to attach the gif images it gives me the png file URL as a response. below is the code
image.onload = function() {
var MAX_WIDTH = 500;
var MAX_HEIGHT = 500;
var tempW = image.width;
var tempH = image.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement("canvas");
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
dataURL = canvas.toDataURL();
dataURL = dataURL.replace(/^data:image\/(png|jpg|gif);base64,/, "");
$.ajax({
url: 'https://api.imgur.com/3/image',
type: 'post',
headers: {
Authorization: 'Client-ID *************'
},
data: {
image: dataURL
},
dataType: 'json',
error: function(response) {
console.log(response);
},
success: function(response) {
if (response.success) {
console.log(response.data.link);
$('#snippet_image').val(response.data.link);
}
}
});
}
What I tried, I have added gif with png|jpg as shown below
dataURL = dataURL.replace(/^data:image\/(png|jpg|gif);base64,/, "");
Hi you are missing the multipart/form-data, mime type in your ajax example:
the html:
<form id="imgur">
<input type="file" class="imgur" accept="image/*" data-max-size="5000"/>
</form>
The js:
$("document").ready(function() {
$('input[type=file]').on("change", function() {
var $files = $(this).get(0).files;
if ($files.length) {
// Reject big files
if ($files[0].size > $(this).data("max-size") * 1024) {
console.log("Please select a smaller file");
return false;
}
// Begin file upload
console.log("Uploading file to Imgur..");
// Replace ctrlq with your own API key
var apiUrl = 'https://api.imgur.com/3/image';
var apiKey = 'ctrlq';
var settings = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json'
},
mimeType: 'multipart/form-data'
};
var formData = new FormData();
formData.append("image", $files[0]);
settings.data = formData;
// Response contains stringified JSON
// Image URL available at response.data.link
$.ajax(settings).done(function(response) {
console.log(response);
});
}
});
});
source code : link
Hope it helps

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==

How to get selected file list in javascript?

I am trying to create a file upload with progress-bar with the help of HTML5. trying to create multiple file-upload. Below is my code. Inside handleFiles function i have one alert statement and its returning 'undefined'. Can anyone help me here...
$('#photoimg').change(function()
{
handleFiles(this.files); alert('got it');
var $fileUpload = $("#photoimg");
if (parseInt($fileUpload.get(0).files.length)>$('#galCnt').val())
{
alert("Maximum of 5 images allowed to upload. Only "+$('#galCnt').val()+" left");
return false;
}
//var formData = new FormData($('#imageform')[0]);
fd = collectFormData();
// Attach the files.
for (var i = 0, ie = PENDING_FILES.length; i < ie; i++) {
// Collect the other form data.
fd.append("file", PENDING_FILES[i]);
}
// Inform the back-end that we're doing this over ajax.
fd.append("__ajax", "true");
$("#imageloadstatus").show();
//$("#imageloadbutton").hide();
var $progressBar = $("#progress-bar");
$progressBar.css({"width": "0%"});
var xhr = $.ajax({
xhr:function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener("progress", function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// Set the progress bar.
$progressBar.css({"width": percent + "%"});
$progressBar.text(percent + "%");
$("#loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
}, false)
}
return xhrobj;
},
url: SITE_URL+'/index/ajax',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$progressBar.css({"width": "100%"});
$("#imageloadstatus").hide();
$('#preview').html(returndata);
}
});
});
var PENDING_FILES = [];
function collectFormData() {
// Go through all the form fields and collect their names/values.
var fd = new FormData();
$("#imageform :input").each(function() {
var $this = $(this);
var name = $this.attr("name");
var type = $this.attr("type") || "";
var value = $this.val();
// No name = no care.
if (name === undefined) {
return;
}
// Skip the file upload box for now.
if (type === "file") {
return;
}
// Checkboxes? Only add their value if they're checked.
if (type === "checkbox" || type === "radio") {
if (!$this.is(":checked")) {
return;
}
}
fd.append(name, value);
});
return fd;
}
function handleFiles(files) {
// Add them to the pending files list.
for (var i = 1; i <= files.length; i++)
{
alert(files[i]);
PENDING_FILES.push(files[i]);
}
}

Ajax send & Save Base64 encoded image to server

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

Categories

Resources