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

我的未来我决定 提交于 2021-01-27 23:31:47

问题


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,


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/51198882/how-to-recieve-image-blob-data-by-cropper-js-in-laravel-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!