How to recieve image blob data by Cropper Js in laravel controller - javascript

I am working with cropper js and laravel, I cropped the image and put it into the formdata and send it to the Laravel controller by Jquery Ajax.
The problem it that I do not get data in controller. but only get an error.
the code is given below:
HTML
<button type="button" name="button" id="crop">Crop</button>
<img src="{{asset('public/img/img.jpg')}}" id="image" alt="" style="height: 500px;">
Jquery and Cropper Js Code
<script src="{{asset('public/js/jquery.min.js')}}"></script>
<script src="{{asset('public/js/cropper.min.js')}}"></script>
<script type="text/javascript">
$(document).ready(function(){
var ele = document.getElementById('image')
var cropper = new Cropper(ele);
$('#crop').on('click', function(){
var crop = cropper.getCroppedCanvas();
crop.toBlob(function(blob){
var formdata = new FormData();
console.log(blob);
formdata.append('croppedImage', blob);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax("{{url('crop/save')}}", {
method: "POST",
data: formdata,
enctype: 'multipart/form-data',
cache: false,
processData: false,
contentData: false,
success(data){
console.log(data);
},
error(data){
console.log(data);
},
});
});
});
});
</script>
Laravel Route
Route::post('crop/save', 'CropperController#save');
Laravel Controller
public function save(Request $request){
$data = $request->croppedImage;
var_dump($data);
//Here I want to get image and upload it on the system
//But I cant Understand How
}
Error
<br />
<b>Warning</b>: Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini. in <b>Unknown</b> on line <b>0</b><br />
Please Guide me, How to done this in proper way.
Thanks in advance.
Regards,

You need to create a new image using the blob data and save that.
First, you need to get the actual contents of the image which is everything after: data:image/png;base64, or data:image/jpeg;base64,
(You can use the first part of the blob to get the extension type so you can save out the image using the same extension later.)
This will do that:
$base64Str = substr($data, strpos($data, ",")+1);
Next, you need to decode the contents as it is in base64
$file = base64_decode($base64Str);
Then, specify the path to save the new image. You can use a random generator combined with the current timestamp to get a unique name for each file.
public function generateUniqueFileName($extension)
{
return md5(uniqid(rand(), true)) . '-' . md5(microtime()) . '.' $extension;
}
$fullPath = 'public/images/' . $this->generateUniqueFileName($extension);
Finally, you can store the image to the specified path:
Storage::put($fullPath, $file);

You can try this too, since the url from your AJAX is a post request, go to app/Http/Middleware/VerifyCsrfToken.php and do this
protected $except = [
'crop/save'
];
Then in your controller you can save the image like this
public function fileUpload(Request $request){
$file = $request->file('croppedImage');
if($file) {
$file->move(public_path() .'/images', $filename);
}
}
OR
public function fileUpload(Request $request){
$file = $request->file('croppedImage');
if($file) {
Storage::disk('local')->put($filename, File::get($file));
}
}
If you are using the second way, don't forget to do this at the top of the controller'
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
The $filename variable is the name you choose to save the file with.

Related

Where do PHP echos go when you are posting to a page?

This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)

AngularJS - How to send an audio file through $http post?

So I've been trying to send an audio file through an $http service using FormData, and so far what I have tried to send the file hasn't worked yet.
This is how the service looks like:
songs_services.add_new_song = function(new_song_name, new_song_artist, song) {
var fd = new FormData();
fd.append("new_song_name", new_song_name);
fd.append("new_song_artist", new_song_artist);
fd.append("song", song);
console.log(fd.get("new_song_name"));
console.log(fd.get("new_song_artist"));
console.log(fd.get("song"));
return $http.post(BACKEND_PREFIX + "add_new_song", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function() {
}, function() {
});
};
I wanted to make sure that the information was actually been appended to my FormData and this is what i get in the console:
So now I know that the FormData has actually the information that I need.
I have also tried changing the Content-Type to multipart/form-data with no success also.
I'm also using CakePHP 2 as my backend, so this is how I'm trying to get the information:
public function add_new_song() {
$this->autoRender = false;
$data = json_decode(file_get_contents("php://input"));
print_r($data);
print_r($_POST);
print_r($_FILES);
$new_song_name = $_POST["new_song_name"];
$new_song_artist = $_POST["new_song_artist"];
$song = $_FILES;
echo $new_song_name;
echo "<br />";
echo $new_song_artist;
echo "<br />";
print_r($song);
die();
}
But echoing the variables only shows empty arrays and I also get an undefined index error when trying to access the variables from $_POST.
Is there any special way I should be sending the audio file through $http? I really feel like I'm missing a little detail.
At last, instead of using angularjs $http.post I decided to try with $.ajax and see what happened, and it actually worked!
Here's what I used:
$.ajax({
type : "post",
url : "uploads/songs",
data : fd,
cache : false,
contentType : false,
processData : false,
success: function() {
console.log("Hey");
}
});
And in Angular 6, you can do the following to send audio as FormData.
Inject the HttpClient:
constructor(private http:HttpClient){}
Use the POST method to send audio:
let url = 'http://destinationurl.com/endpoint';
let formData = new FormData();
formData.append('myAudioFile',audioFile);
this.http.post(url,formData).subscribe(response => {
//handle response
}, err => {
//handle error
});
the post method will automatically change the content type to multipart, so you need not set anything manually.

Getting a PNG image from PHP using AJAX

I have a PHP script that computes the next value in a time series data and plots that to a graph as a PNG image. I will provide this data through AJAX, and PHP creates the PNG image. Now, how do I get the generated PNG image from PHP as an AJAX response? The code is as follows:
PHP:
<?php
$data = json_decode($_POST['data']);
// Some code to calculate the next value in this series
plotRenderRegression( $polynomialRegression, $coefficients, 0, 11 , $colorMap[ "Blue" ] );
header( "Content-Type: image/png" );
echo imagePNG( $image );
?>
JS:
$.post({
dataType: "image/png",
url: "predict.php",
data: {
sent: true,
data: "[[1,0.63151965],[2,0.58534249],[3,0.43877649],[4,0.2497794],[5,0.07730788],[6,0.08980716],[7,0.11196788],[8,0.19979455],[9,0.4833865],[10,0.9923332]]"
},
success: function (img) {
console.log(img)
i = new Image();
i.src = img;
console.log(img);
$("#imgdiv").prepend(i);
},
error: function (error, txtStatus) {
console.log(txtStatus);
console.log('error');
}
});
Console Output:
�PNG
IHDRX�Ao�NPLTE������00�������000������������333MMMfff���������������vD���IDATx��][��*�*>���o���$ ?$[��ɑq� Ι�����������2������Fp�;D33������c���وeĪF�iO̮H�����r*3'���[N
o~p#���X��ˀ���ub��T�X�,���׽���q�.�R��}� �]��#æy����l}�
}:U���,�����'�w�W_�0S9ԡ�wl�0�עOfTc8qw��9,=�s����7��^��h�U�1b-��?��鎿G����Ag��}����7Gg��GY���R��4y� LE����8'o� �+L>A��ʻ�e�hry��سد�끷�j����`#�����)ժϜΟc-)_ck��� ���=2�W�rY�X�gY]���1�H�T�3�*�]'�V�T̼t$���ྑN��&�K���%qp�cuf���2}8����`�PA'VF%6�PoC-6!���ky����8䪏U�:������,�Ƌ�
�9Uby���W�
���共� .....
What am I doing wrong here ?
UPDATE 1:
I've changed the JS code as follows, but it still get a broken image
success: function (data) {
$('#imgdiv').html('<img src="data:image/png;base64, ' + btoa(unescape(encodeURIComponent(data))) + '" />');
}
You can't set SRC to the image itself. You can solve the problem in two ways:
1- Create a temporary file and return a link to it in your PHP file
2- base64 encode the PNG and pass it to src the way you're currently doing.
On both those ways, you'd probably have to lose the "dataType" filter of jQuery for the response to be interpreted as successful.
Example of final HTML (src set via your JavaScript Ajax):
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC />"
<img src="data:image/png;base64,[base64_encoded_png_goes_here] />"

Passing image from form to wordpress using ajax without any plugin

I have made a form on my wordpress theme through which i want user to upload image .This is my HTML
<input type="file" id="file" />
<button id="uplod" ">Upload</button>
and below is my js
jQuery("#uplod").click(function()
{
console.log("trying to fetch image");
var selectedFile = jQuery('#file').get(0).files[0];
console.log(selectedFile);
var ajaxdata=
{
action:"reg_upload_img",
img:"selectedFile"
}
jQuery.post(ajaxurl, ajaxdata,function(res)
{
jQuery(".divError").html(res);
});
});
and my function in functions.php file of theme is
function fiu_upload_file(){
$error = '';
var_dump($_FILES);
wp_die();
}
add_action('wp_ajax_reg_upload_img', 'fiu_upload_file');
add_action('wp_ajax_nopriv_reg_upload_img', 'fiu_upload_file');
what should i add in my js code and php code so that image of form can be passed to my wordpress directory so that i can save and handle it in wp database
You can't upload files with jQuery.post(), only XMLHttpRequest can be used with FormDataand jQuery.ajax() can be used which uses XMLHttpRequest internally.
jQuery("#uplod").click(function(e) {
e.preventDefault();
var fd = new FormData($("#file"));
fd.append("action", "reg_upload_img");
fd.append("img","selectedFile");
$.ajax({
url: url,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
});
and a small typo with your button's attributes, you have an extra ":
<button id="uplod">Upload</button>
//----------------^-----------one extra '"' removed from here.

jQuery and Ajax Loading Images

I have a site with a giant portfolio with a ton of high-res images.
I do not want to resize these images, but I would like to be able to pull them in async.
Come forth jQuery .ajax
But my code is wrong, somehow. What it does is seem to pull in the page, instead of the image "src"
Can you help:
// Load in the images via ajax:
var $imgs = $('.ajax-image');
$imgs.each(function(i){
var $imgsrc = $(this).attr('src');
var $url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
$(this).attr('src', html);
}
});
});
and the PHP:
$path = $_GET['i'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
echo 'data:image/' . $type . ';base64,' . base64_encode($data);
Image tags are simply: <img src="http://example.com/images/image.ext" />
What am I doing wrong here? and how can I fix it?
As I mentioned in my comment, I don't see how this would do what you want but to address your current problem: It is probably caused because of this in the context of the success function, is not the same as the this in the context of your each() function.
You should save the element so that you can access it in the success function:
$imgs.each(function(i){
var el = $(this),
$imgsrc = el.attr('src'),
$url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
el.attr('src', html);
}
});
});
Edit: There is no real need to use ajax / php here to set the source of the image. You could also generate some images in javascript (in batches), add an onload() function for the images and set the source of your html elements when they are loaded and then get the next batch. See for example this question: JavaScript: Load an image from javascript then wait for the "load" event of that image
Your php page is getting an error because you are not passing in anything for parameter i. Your php is therefore throwing a 404 error - a full HTML response.
I think you have a javascript syntax error that is causing this:
url : '/php/pull-image.php?i=' . $imgsrc,
Replace this line with:
url : '/php/pull-image.php?i=' + '<?php echo json_encode($imgsrc); ?>' ,

Categories

Resources