Saving a base 64 image creates a blank image in PHP - php

First here's my client side code:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
img.onload = function(){
canvas.width = 600;
canvas.height = 400;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
}
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
})
And here's my php code:
$imageArr = explode(',', $_POST['image']);
$image = base64_decode($imageArr[1]);
file_put_contents('image.jpg',$image);
I'm resizing the image on the client side and then sending it as a data url to php to then be saved as an image.
When I save an image it creates a blank image on my server. BUT when I save another image without refreshing the page it saves the previous image in it's place and this time correctly. This is beyond me, can someone please shed some light?

You are sending the image before it is loaded. Your img.onload function is executed after xhttp.send(data). When you upload one more time it gets previous image which is already loaded.
Try following:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 400;
var ctx = canvas.getContext('2d');
img.onload = function(){
ctx.drawImage(img,0,0,canvas.width,canvas.height);
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
}
})

A possibility to keep in mind: Since everything on client side is setup in the file input's onChange event handler, maybe some setup code is launched in the wrong order and/or not in time to be used as intended? Then, when invoking the onChange event again, resources are already in place /has already been initialized and the image gets displayed as intended.
It's just a theory. To investigate, try to move initializations out of the event handler scope.

Related

Download button under all images WordPress

I have a WordPress site with a huge number of images and I want to add the ability to download each one. they are contained in posts (one post contains 50-100 images). I tried using the "Files Download Delay" with the search by file extension feature, but the button doesn't appear.
Are there any template scripts? or how can the idea be realized?
Thank you
jQuery(".wp-block-image").each(function() {
var imageurl = jQuery(this).find("img").attr("src");
var download_html =`<div class="download-link">
<a href="javascript:void(0);"
id="download_nopurchased" class="click_download icon-download" data-
href="${imageurl}" download="${imageurl}" data-url="${imageurl}"><i
class="fas fa-download"></i> Download Now </a>
</div>`;
jQuery(this).append(download_html);
});
jQuery(".click_download").click(function() {
var file = jQuery(this).data("url");
var file_name = getFileName(file);
forceDownload(file,file_name);
});
function getFileName(str) {
return str.substring(str.lastIndexOf('/') + 1)
}
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}

Combining XHR request with form test after resizing an image to be uploaded

I am trying to send both form input text and an image that is being uploaded and resized client side to a php page.
The image is sending fine but when I try to append the text data, it won't work.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev){
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'uploadResized.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = new FormData();
data = 'image=' + dataURL;
data.append('Name', 'test');
xhr.send(data);
When I tried appending a string to test it, the data isn't sent at all. However without the append it still sends. How do I append the information?
I think when you do data = 'image=' + dataURL;, you redefine the var data as a string. So the append method for the name is failing. I think you have 2 options:
1: Using the formData() constructor:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev){
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'uploadResized.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = new FormData();
data.append('image', dataURL);
data.append('Name', 'test');
xhr.send(data);
2: Not using the formData() constructor:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev){
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'uploadResized.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL + '&Name=test';
xhr.send(data);

I want to make this similar HTML structure in jQuery function dynamically and append to html tag id="images"

I am uploading images and want to show separate progress bar for each image.
This kind of similar structure I want to create dynamically in jQuery. Here I m trying to create img element uploaded by input file and want to create html container classname 'preview' and put into already created #images tag by using jQuery. Will you please anyone fix it? so frustrated and thanks in advance to all intelligent brains here.
<div id="images"> // already exist
<div class="preview" id="rand">
<img src="background/balance.jpg" id="rand"/>
<div class="progressbar" id="rand">
</div> // this is the preview container to create and put by dynamically in jQuery function
</div>
this is my jQuery function.
function handleFile(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileReader=new FileReader();
var rand = Math.floor((Math.random()*100000)+3); /* this is created for assign id attribute to div and img tag to differentiate each other */
var imageElem=document.createElement("img");
imageElem.id=rand;
var div = document.createElement('div');
div.className = 'preview';
div.id = rand;
var progress = document.createElement('div');
progress.className='progressbar';
progress.id=rand;
fileReader.onload = (function(img)
{
return function(e)
{
img.src = e.target.result;
};
}) (imageElem);
/* here I am trying to create that structure */
document.getElementById("images").appendChild(imageElem); /* and need to append here */
fileReader.readAsDataURL(file);
// document.getElementById("areatext").style.display = "none";
document.getElementById("submit1").style.display = "block";
document.getElementById("submit2").style.display = "block";
uploadFile(file,rand);
}
}
function uploadFile(file,rand) {
var xhr = new Array();
xhr[rand] = new XMLHttpRequest();
var formData = new FormData();
formData.append('myFile[]',file);
xhr[rand].upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
$(".progressbar[id='"+rand+"']").css("width",(e.loaded / e.total) * 100 + "%");
}
}, false);
xhr[rand].open("POST", "drop.php");
xhr[rand].overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr[rand].send(formData);
}

Kinetic JS not working in Firefox

I have used one script. My problem is script is not working in Firefox browser.
Code is here:
window.onload = function(){
var stage = new Kinetic.Stage({
container : "cantainer",
width : 400,
height : 400
});
var layer = new Kinetic.Layer();
stage.add(layer);
var con = stage.getContainer();
var dragSrcEl = null;
//image
document.getElementById("yoda").addEventListener('dragstart',function(e){
dragSrcEl = this;
});
con.addEventListener('dragover',function(e){
e.preventDefault(); //#important
});
//insert image to stage
con.addEventListener('drop',function(e){
var image = new Kinetic.Image({
draggable : true
});
layer.add(image);
imageObj = new Image();
imageObj.src = dragSrcEl.src;
imageObj.onload = function(){
image.setImage(imageObj)
layer.draw()
};
});
Check the script on link: http://jsfiddle.net/lavrton/n4w44/
Thanks for help in advance.
Add
e.preventDefault();
inside drop event listener.
Demo: http://jsfiddle.net/bk86e/

Passing a image size variable using Javascript to a PHP page

I am trying to send a canvas drawing to the server using javscript.
Having a function such as :
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
window.location = "myPHPfile.php?imageData=" + imgData;
}
What would the best way to pass the imgData variable to the php page due to its large size.
Thanks in advance!
User post request to pass large data. You can use jQuery post method
$.post('myPHPfile.php', { imageData: imgData }, function(data) {
// completed
});
Or create and post form:
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
var form = document.createElement('form');
form.method = "POST";
form.action = "myPHPfile.php";
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = 'imageData';
hidden.value = imgData;
form.appendChild(hidden);
document.body.appendChild(form);
form.submit();
}

Categories