uploading web generated image in require.js module - javascript

I am using a web labeling tool to generate image from the website, however I want to modify the function so that when I am done with labeling, instead of downloading the image to local, I want it to be uploaded into server. The function is in a javascript file and all the upload associated with JS has to do with submitting forms. There is no form and super globals, how am I supposed to upload a web generated image to server?
here is the code I currently have, it is not in html file, it is in js file.
var file_data = annotator.export();
var formData = dataURItoBlob(file_data);
var fd = new FormData(document);
fd.append("resultImage",formData);
url="upload/";
http.open("POST", url, true);
// headers
http.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
http.setRequestHeader("Content-length", fd.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(fd);
php file
<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Really appreciate your help, thank you.

dataURItoBlob(file_data); by the name of the function it looks like that is going to be returning a blob object. blob/file objects when uploaded to a php script are going to be in the $_FILES global, not $_POST. And you would use move_uploaded_file to move it to your desired destination.
Also you seem to be using the wrong index. You are using hidden_data in your php but you set the name to resultImage in your javascript. You would need to use the same name in php as you did in the javascript.
So your php code should look something like
$upload_dir = "upload/";
$img = $_FILES['resultImage'];
if($img["error"] == UPLOAD_ERR_OK){
//should do other sanitation like making sure the file
//that is uploaded is the actual type of file you expect
$path = $upload_dir . mktime() . ".png";
move_uploaded_file($img["tmp_name"], $path);
}
As a side note, when using and FormData object you do not need to set the request headers like Content-Type as they will automatically be set by the api.

Related

How can i pass formData object through post and receive it in other php file

How can i pass formData object through post and receive it in a php file , trying to upload a image file through ajax php .
My html , js file looks like this
<input type="file" id="myFileInputId" name="myFileName">
var the_file_that_was_uploaded = profile_image_input.files[0];
var form_data_obj = new FormData();
form_data_obj.append('fileToUpload',the_file_that_was_uploaded);
form_data_obj.append("id_of_user", myId);
form_data_obj.append("text_of_quake", myTextvalue);
xhr.onload = function(){
if(this.status == 200){
console.log(this.responseText);
}
};
xhr.onerror = function(){
console.log('Error from server side');
}
xhr.open('POST','myPHPbackEnd.php',true);
xhr.send('some_information='+form_data_obj);
in my php file , want to do this
if(isset( $_POST['some_information'])){
//how to get the file and its porperty
//cannot get to $_FILES['some_information']
//or $_FILES['myFileName']
//or id and text
}
I want to get the formData object and its content and pass it to a next php file for doing something like this , but cannot relate all of them together
$fileName = $_FILES['fileToUpload']['name'];
$fileType = $_FILES['fileToUpload']['type'];
$fileContent = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$value = $_FILES['fileToUpload']['tmp_name'];
$targetPath = 'temp_image_folder/'.basename($_FILES['fileToUpload']['name']);
move_uploaded_file($value,$targetPath);
Change your js code to:
xhr.send(form_data_obj);
Then in your php do:
if(isset($_FILES['fileToUpload'])){
// do stuff with file
}

File is corrupted after converting

I am using recorder.js library and want to send the recorded message to my gmail account using PHPMailer. I have done everything but the only problem that I am getting is that when I send the file as an attachment and download it from my mail, it is corrupted (or whatever) and my system says "The file is unplayable". Moreover, when I check my local uploads/ folder where I am writing all the files, they are unplayable too. I don't know what seems to be the problem and I am stuck on this since past two days. Thanks in advance.
My JS call to upload.php
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
and my upload.php
<?php
require "php-mailer-master/PHPMailerAutoload.php";
define('UPLOAD_DIR', 'uploads/');
$a = $_FILES['audio_data']['name'];
$a = str_replace('data:audio/wav;base64,', '', $a);
$a = str_replace(' ', '+', $a);
$data = base64_decode($a);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Please note that I have skipped the part of code which is actually sending mail because I believe that is irrelevant.

Saving a file on server using JavaScript

Js code
var server = '';
var orig_chat = chatUpdateSucess;
chatUpdateSucess = function(o){
if (o.GlobalChats && o.GlobalChats.length > 0) {
//TODO: Add setting to enable/diosable this
console.log(JSON.stringify(o.GlobalChats));
var xhr = new XMLHttpRequest();
xhr.open("POST", server+"/api.php?request=log_gc");
xhr.send(JSON.stringify(o.GlobalChats));
}
orig_chat.apply(this, arguments);
};
Server code named api.php
<?php
header("Access-Control-Allow-Origin: *");
if(!empty($_POST['o.GlobalChats'])){
$data = $_POST['o.GlobalChats'];
$fname = time() . ".txt";//generates random name
$file = fopen("" .$fname, 'w');//creates new file
fwrite($file, $fclose($file);
}
?>
console.log output
[{"PlayerId":237186,"toPlayerId":0,"chatid":16606292,"added":"/Date(1451764948837)/","addedText":"20:02","PlayerLink":"p=Kodabear|237186|T?|78|1|0|0-144-0-240-186-0-0-0-0-0-0-0-0|#IKnowAFighter|Neurofibromatosis Awareness day/Month|5-404-282-59","text":"Exmaple of a real chat"}]
I created a js that sends a file to my server every time the chat in the game is updated. But I am having problems with the server side code any advice would be great help. (PHP code was founded here
Saving a text file on server using JavaScript
Try to var_dump($_POST['o.GlobalChats']) to see if your data is reaching the server.
It seems like you are not writing the file to the system properly. Please read the examples at the manual (http://php.net/manual/pt_BR/function.fwrite.php)
Also, using time() is not safe, because two files may be created at the same UNIX timestamps in extreme cases, and one will overwrite the other
Try something like this:
$data = $_POST['o.GlobalChats'];
$fname = time() . "-" . rand ( 1 , 10000 ) . ".txt";
$handle = fopen($fname, 'w');
fwrite($handle, $data);
fclose($handle);

ajax json send an image and other data to a remote server

I have a problem that I can not solve (it is probably also your case if you read this).
I would like to send JSON data to a remote server via AJAX. This data contains an image and a string:
{
"question": "Your SquareOff Question",
"photo" : "Your photo" // optional
}
I need to send this JSON to "www.so-staging.herokuapp.com/api/v1/squareoffs?auth_token=qSJPySVk5yMsaAVE6mSu" where "qSJPySVk5yMsaAVE6mSu" is a token that I had previously ask for it and store in the $_SESSION, in a php side.
So I need to send this information to my php page before send it to the remote server. And here is my problem. I can receive the image in my php page, but not re-send it to the remote server.
I show you my code.
On the Html side, nothing special:
On the javascript page:
I don't know and to send the image and the string in the same time so. (if you have a hint, it would be with pleasure but it is not my mane problem).
function upload_photo(){
var photo = document.getElementById('photo');
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append('photo', photo.files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'create_square.php');
xhr.send(formData);
/* Check the response status */
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && client.status == 200){
create_square_xhr();
}
}
}
function create_square_xhr(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'create_square.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && client.status == 200){
// response is a iframe who display my question and my image if I have
// send one. I display it.
}
};
xhr.send('question=' + document.getElementById('question').value;
}
upload_photo();
And on my php page (create_square.php):
if(isset($_SESSION['token']) && isset($_POST['question']) && isset($_FILES['photo'])){
$url = 'https://so-staging.herokuapp.com/api/v1/squareoffs?auth_token=' . $token;
$data = array('question' => $_POST['question'], 'photo' => $_FILES['photo']);
$data = json_encode($data);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n" .
"Accept: application/json\r\n",
'method' => 'POST',
'content' => $data
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo &result;
}
The response is an iframe who dispay my question and my photo if I have send one.
But when I execute this code, there is no image displayed.
I think the probleme is on the php page because I recive the $_FILES['photo'].
If you have any suggestion, I will be grateful. Thank you!
I would suggest adding a check for errors by checking: $_FILES["photo"]["error"], which may tell you if there is an issue with the photo upload.
You also have to remember that when uploading photos with PHP that it is uploaded with a randomly generated name that you typically need to move to the final location before you do anything else with it.
This is typically what you need to do in order to have access to the photo once it has been uploaded.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
echo $_FILES["photo"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"],
"upload/" . $_FILES["photo"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["photo"]["name"];
}

when saving canvas image server-side, from a base64 data string,it produce blank image

I have problem with saving canvas image in PHP. I get a blank .png file. I search a lot about this problem but cant find anything useful about this. Why does it save a blank image instead of rendering real image?
JavaScript code:
html2canvas([document.getElementById('dadycool')], {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var image = new Image();
image.src = data;
document.getElementById('imagec').appendChild(image);
console.log(data);
$.ajax({
type: "POST",
url: "up.php",
data: {
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
}
PHP code:
<?php
// requires php5
define('localhost/samp/sample2/uploads', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I suspect you haven't configured your development box to display PHP error messages. You are defining a constant that is not a valid identifier:
define('localhost/samp/sample2/uploads', 'images/');
That means that you cannot use it directly:
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
... should be triggering:
Notice: Use of undefined constant localhost - assumed 'localhost'
Notice: Use of undefined constant samp - assumed 'samp'
Warning: Division by zero
Notice: Use of undefined constant sample2
Warning: Division by zero
Notice: Use of undefined constant uploads - assumed 'uploads'
Warning: Division by zero
... and file will only contain the base file name (e.g. 53676a01cdb59.png) but not path component. You need to use this syntax:
$file = constant('localhost/samp/sample2/uploads') . uniqid() . '.png';
... or, even better, give the constant a sensible name:
define('DIR_UPLOADS', 'images/');
I was having this same issue - it looked like the base64 data was being sent correctly but always failed to generate the image server side. The solution I found was to use the 'FormData' object and a very simple xhr request to post to the server.
var url='/path/to/save.php';
var data=oCanvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
var fd=new FormData();
fd.append('imgdata',data);
var request = new XMLHttpRequest();
request.open('POST', url);
request.send(fd);
I'm 99% sure the problem was caused by the incorrect Content-Type header being sent by the xhr request. Using a basic xhr request combined with FormData forced the xhr request to be sent with the multipart/formdata content type with correctly defined content boundaries.

Categories