Send base64 image from meteor application - javascript

I have a meteor application and in this one I use cropper plugin to upload an image from the local computer of the user in the website and after send it to my DigitalOcean server. So the upload from the local computer works but when I try to send the image in my server, it doesn't work.
From cropper plugin, I retrieve a imgbase64 I want to send.
I search on many forums but I didn't find a good solution so I tried to do this :
In myapp.js I have :
$("#save").click(function() {
window.open($image.cropper("getDataURL"));
var dataURL = $image.cropper("getDataURL");
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
});
In myapp.html I have
<button class="btn btn-primary" id="save" type="submit">Save</button>
And I have a php script :
<?php
// requires php5
define('UPLOAD_DIR', '/home/images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
//header('Location: '.$_POST['return_url']);
?>
When I click on save button, I get "saved" in the console but I have nothing in the folder.
Do you have an idea why ?

I'm afraid it looks like you aren't using Meteor correctly.
Meteor is a JavaScript framework, so you can't create PHP files and try to initiate them within Meteor. All of your code has to be JavaScript.
This is a fundamental part of meteor development. I suggest you try the Meteor tutorial which should help you learn how to use Meteor.
The code you have posted will not achieve what you want to achieve, you will need to remove the PHP and rewrite it in JavaScript.

Related

Give the result of canvas.toDataURL (JS) to $mail->addAttachment(); (PHP)

I'm developing a webapp where the user will be able to configure a pool by dragging the various icon on a blueprint (stairs, skimmer, light...).
Once the configuration is done, the user can click on a button to receive the blueprint by email.
I did the function that take the screenshot and it works well, i did also the PHP function that send the mail (made with PHPmailer) and it work too.
My problem is that I can't find a way to attach the result of my screenshot which is stored in the JS variable "url" and gave to the html in the id "linkImg" :
function getPNG(){
html2canvas(document.querySelector("#plan")).then(canvas => {
document.getElementById("box1").appendChild(canvas)
var url = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const linkImg = document.getElementById("linkImg");
linkImg.href=url;
linkImg.download="plan.png";
});
}
Here the code of php part that i need to fill :
<?php
$mail->addAttachment();
?>
I tried to give as argument : '$(#linkImg)' but without surprise it does not work.
I thank you by advance for any help. Have a good dayy
The image is in the browser, but your PHP code is on your server, so you have to pass the image data from the browser to the server. The best way to do that is with fetch. Here's an example showing how to send canvas data using fetch. On the server side, you will need to decode the data URL:
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
and then you will be able to add it to your email message directly, without going via a file, using addStringAttachment():
$mail->addStringAttachment($data, 'image.png');

Upload blob audio file to aws ec2-instance using php

I am creating a web application where user can record audio and then can upload it to the server.
I am able to record the audio and also was able to send the blob data to the server. But i cannot push file into the ec2-instance (aws hosting enviornment). I am attaching the php code.
I am not sure which path should i use.
Here is the Php Code.
<?php
print_r($_FILES);
$uploaddir = '/var/www/html/public/src/audio/';
$uploadfile = $uploaddir . basename($_FILES['audio_data']['name']);
$size=$_FILES['audio_data']['size'];
$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav";
if(move_uploaded_file($input, $$uploadfile)){
echo "uploaded";
}
else{
echo $uploadfile;
}?>
Is there a way to push data and create file on hosted aws-ec2 instance? Is there any changes required in the php file?
This is the image of response from server

Uploading image from webcam to server

made a websitem, or trying to, where you can take a picture with your webcam and then upload it to the server, but ive found some inspiration in a guy that uses PHP and i wanna avoid it as much as posible. so what i have now in my .html for uploading is the picture is:
// Upload image to sever
document.getElementById("upload").addEventListener("click", function(){
var dataUrl = canvas.toDataURL("images/", 0.85);
$("#uploading").show();
$.ajax({
type: "POST",
url: "html5-webcam-save.php",
data: {
imgBase64: dataUrl,
//user: "Joe"
}
and then the reference(html5-webcam-save.php):
<?php
$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$datime = date("Y-m-d-H.i.s", time() ) ; # - 3600*7
//$userid = $_POST['userid'] ;
// name & save the image file
$fp = fopen('images/'.$datime.'-'.$userid.'.jpg', 'w');
fwrite($fp, $unencoded);
fclose($fp);
so my question, anyone now how to upload it to the server or just the "images" folder in the root of the site, without the need for PHP.
to be honest, the reason i dont want the PHP is because i simply cant get it to work properly on the server side, and iam lost when it comes to php. So can this be done with for instance C#/Javascript?
"..without the need for PHP"
You can't. You need a server side language to receive the data from raw http, convert it back from base64 text to image and then write it to disc. It could be PHP, c#, nodejs javascript, but there will always be a server side controller handling all this. You can't access server file system from client javascript for obvious security reasons.

saving dataURL image locally via php

I'm making a PNG image file from a dataURL string (thanks to the example from The PHP manual). I'd like this code to open the "Download file" dialog in the browser, so users can save this image locally, but calling the function imagepng() saves the image to my server instead. Am I using the wrong function when calling imagepng()? I'm trying to trigger a download by changing the headers, but it's still saving to the server.
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
// set the headers, to trigger a download
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
imagepng($im, 'test_2.png');
imagedestroy($im);
?>
Also, I'm calling the PHP via the following JavaScript, (not sure if this is relevant to the results I'm getting)
$.ajax({
type: "POST",
url: "php/downloadimg.php",
dataType: 'text',
data: {
data : finishedImage.src
}
})
just call the imagepng function without the second parameter. if you follow the imagepng documentation you read that filling in the second parameter the image is saved to this filename.
pass only the image resource to the function and the raw image are send to the client.
http://php.net/manual/de/function.imagepng.php
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
if you use php only files don't use the php close tag ?> to avoid leaked whitespaces and messed up your output stream.
It's worth noting that since you've already got the image data in PHP, there's no need to call the imagepng function or anything like it. All you need to do is dump your image data to the client after you set the headers, which will then decide for itself what to do with it.
So, something like this will work if you don't need to actually process the image server side:
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
// set the headers, to trigger a download
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
echo $data;
?>

Moving a photo uploaded with Dropzone.js and PHP

I'm trying to use dropzone.js to add an easy drag-and-drop interface for a user to upload up to 10 photos to my server (currently WAMP). I'm using PHP 5.4 on the back end.
Following this tutorial I got the system working enough to upload acceptable file types to an 'Uploads' folder in my root directory, but I'm stuck on how to make the photos instead upload to a unique directory for each user.
By the time the user gets to my photo upload page, they've already created a folder on my server with a unique name, the path to which has been stored in $_SESSION['requestedDirectory'].
Here is the code used to display the Dropzone form:
<form action="<?php echo BASE_URL; ?>photo_uploads.php" class="dropzone" id="photoUploadDropzone"></form>
<script type="text/javascript">
Dropzone.options.photoUploadDropzone = {
paramName: "file",
maxFilesize: 5, // MB
maxFiles: 10,
addRemoveLinks: true,
acceptedFiles: "image/jpeg, image/jpg, image/png, image/gif",
accept: function(file, done) {
done();
}
};
</script>
As you can see, it sends the data to a file called photo_uploads.php, which has the following code:
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = $_SESSION['requestedDirectory']; <--HERE'S THE PROBLEM LINE
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
As mentioned in the comment above, this file doesn't seem to be able to take data out of a session variable, but I'm not sure why. If I change that line to give the full directory (eg $targetPath = 'C://wamp/www/shops/foldername';) it works fine, but then of course I can't change that foldername dynamically based on which user is using the form.
So to clarify, I'd like to know how to upload the file to the path stored in Session?
UPDATE: Solved.
For anyone else with the same problem in future, this is what I changed the form to:
<form action="<?php echo BASE_URL; ?>photo_uploads.php?folder=<?php echo $_SESSION['photosDir']; ?>" class="dropzone" id="photoUploadDropzone"></form>
Like Rizwan suggested, by passing the $_SESSION['photosDir'] value in a GET variable it was accessible after the form posted.
The other change I made was to photo_uploads.php, just to the following line:
$targetPath = $_GET['folder'];
Absolutely no idea why the value wasn't available directly from Session in the first place - I've never heard of Session values going out of scope - but happy to have this problem solved.
You can pass the requestedDirectory as a query string with the form's action attribute. In that way it can be accessible.

Categories

Resources