Pass Base64 with POST Request - javascript

I am using javascript and I get a image file and encode it to base 64 like this
function el(id){return document.getElementById(id);} // Get elem by ID
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
el("img").src = e.target.result;
el("base").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("asd").addEventListener("change", readImage, false);
Where the encoded text is this and looks like this
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gxYSUNDX1BST0ZJTE.........
And now I want to send this data with a post which I know how to do, but when I read the data I sent on the other side I just see data:image/jpeg, where does the Base64 encoded start and how can I just pass that as a string?
I make the post like this
var base64data;
//base64data is declared in the function readImage and I log it in this one and it has data
function callHttpReq () {
var http = new XMLHttpRequest();
var url = "/admin/website_sql/save_info.py";
var params = "website_photo=" + base64data;
http.open("POST", url, true);
console.log(base64data);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
Thanks

Related

How to convert a Canvas image to a Buffered Image for Servlet Processing?

I need to send a HTML-Canvas image from a Webpage to a Servlet for Image Processing. On my webpage, this will be done by uploading a jpg or png image and then clicking a process button.
My frontend is working (I can upload and display images), but I do not know how to send an image from a webpage to a server and vice-versa.
Can you please help me?
HTML: (img stored in canvas)
<canvas id="canvas"></canvas>
JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Ajax Code here???
}
};
xhttp.open("GET", ?, true);
xhttp.send();
Unfortunately, not all browsers does support Canvas.toBlob() function. For example MS Edge and other browsers does not support it (see browser compatibility). Because of this we have to use Canvas.toDataURL() function.
I wrote for you the solution which does the same like normal sending a form from HTML:
var canvas = document.getElementById('canvas'),
dataURL = canvas.toDataURL('image/jpeg', 0.7), //or canvas.toDataURL('image/png');
blob = dataURItoBlob(dataURL),
formData = new FormData(),
xhr = new XMLHttpRequest();
//We append the data to a form such that it will be uploaded as a file:
formData.append('canvasImage', blob);
//'canvasImage' is a form field name like in (see comment below).
xhr.open('POST', 'jsp-file-on-your-server.jsp');
xhr.send(formData);
//This is the same like sending with normal form:
//<form method="post" action="jsp-file-on-your-server.jsp" enctype="multipart/form-data">
// <input type="file" name="canvasImage"/>
//</form>
function dataURItoBlob(dataURI)
{
var aDataURIparts = dataURI.split(','),
binary = atob(aDataURIparts[1]),
mime = aDataURIparts[0].match(/:(.*?);/)[1],
array = [],
n = binary.length,
u8arr = new Uint8Array(n);
while(n--)
u8arr[n] = binary.charCodeAt(n);
return new Blob([u8arr], {type: mime})
}
If you do not know how to save files on server side using JSP, please read:
How to upload files on server folder using JSP
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob) {
var oReq = new XMLHttpRequest();
oReq.open("POST", /*URL*/, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(blob);
},'image/jpeg', 0.95);
}
};
xhttp.open("GET", ?, true);
xhttp.send();
More information:CanvasElement toBlob and Sending Blob

Javascript - How do i submit a canvas in a form?

Basically my problem is that i have a canvas and i want to use the canvas in a form like if it were an image submitted in a input with a type of file, so i can access the $_FILES array..
The project i have made is an image cropping script where a user chose an image file through input type file, and then the script draw the image onto a canvas, then the user can zoom/crop the image... that all works perfectly fine..
But how can i send the cropped image to a php file as form file input data and access the $_FILES super global array?
I really hope someone can help
This link here tries to do something similar to me but i dont understand how it works, or how i could do the same with my project?
Javascript
function convertCanvasToImage() {
var temp_ctx, temp_canvas;
temp_canvas = document.createElement('canvas');
temp_ctx = temp_canvas.getContext('2d');
temp_canvas.width = windowWidth;
temp_canvas.height = windowWidth;
temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);
var dataurl = temp_canvas.toDataURL("image/jpeg");
croppedImage.src = dataurl;
contentCall(dataurl);
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
var params = "profileImage=" + profileImage;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(params);
}
document.getElementById("myfiles").addEventListener("change", pullFiles, false);
document.getElementById("scaleSlider").addEventListener("input", updateScale, false);
document.getElementById("convert").addEventListener("click", convertCanvasToImage, false);
UPDATE
I managed to solve the problem myself
var multiPart = new FormData();
var fileName = "pernille";
multiPart.append('retard', 'christian');
temp_canvas.toBlob(function(blob){
multiPart.append('blobTest', blob, fileName);
contentCall(multiPart);
}, "image/jpg");
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(profileImage);
}
You'll need to store the canvas (as an image) in a hidden form field as its value and then when you submit your form, the image will be submitted.
// Save canvas as dataURL image
var dataURL = canvas.toDataURL('image/png');

Signature does not match s3 GET object

I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance

How to make formData object from image URL

I want to make image upload from url for example: http://.. ../logo.png
I need to make formData object from image url but it doesn't work:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
My php script for debug:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
Thanks for all help and your time..
and sorry for my bad english (student)
If getBase64Image is from here, or is similar to it.
Then you are using it wrong. You need to pass it the image node itself. Also the image onload event is async, and as such you have to wait for it to be done to get the data and send it.
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
Also note on the server side you will need to decode it from the base64 encoding, as it is being sent by string, it is going to be in $_POST not $_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
Note you could also just send the url to the php script and just have php get the image data
var rawContents = file_get_contents($_POST['imageurl']);

Renaming an image created from an HTML5 canvas

I have made a simple canvas and save it as an image. I have done this with the help of this code:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
and pop up the created image with this:
document.write('<img src="'+img+'"/>');
But its name is always a weird one. I want to rename the image name like faizan.jpg etc. How can I do this?
To put it simply, you can't. When you call the toDataURL method on an HTMLCanvasElement it generates a string representation of the image as a Data URL. Thus if you try to save the image, the browser gives it a default filename (e.g. Opera saves it as default.png if the Data URL was a png file).
Many workarounds exist. The simplest one is to make an AJAX call to a server, save the image on the server-side and return the URL of the saved image which can then be accessed and saved on the client-side:
function saveDataURL(canvas) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.location.href = request.responseText;
}
};
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.open("POST", "saveDataURL.php", true);
request.send("dataURL=" + canvas.toDataURL());
}
To save the image on the server side, use the following PHP script:
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/faizan.png", $decodedData);
echo "http://example.com/images/faizan.png";
Got this working 100%! Just had to do a little debugging to the above answer. Here's the working code:
The JavaScript:
var saveDataURL = function(canvas) {
var dataURL = document.getElementById(canvas).toDataURL();
var params = "dataURL=" + encodeURIComponent(dataURL);
var request = new XMLHttpRequest();
request.open("POST", "/save-data-url.php", true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
window.console.log(dataURL);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.console.log(request.responseText);
}
};
request.send(params);
}
/scripts/save-data-url.php:
<?php
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL);
$encodedData = $encodedData[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/log.txt", $encodedData);
file_put_contents("images/test.png", $decodedData);
echo "http://www.mywebsite.com/images/test.png";
?>

Categories

Resources