First setup the Laravel Cloudinary package as explained here
Front End code index.blade.php
<img src="https://helptipsweb.wordpress.com/2021/12/15/laravel-cloudinary-upload-widget-signed-upload/..." alt="..." class="img-thumbnail d-none" id="featured-image"> <button id="upload_widget" type="button" class="btn btn-primary d-none">Upload file</button> @cloudinaryJS <script type="text/javascript"> var generate_signature = function( callback, params_to_sign ) { console.log(params_to_sign); $.ajax({ url : "/cloudinary/secret", type : "POST", dataType: "text", data : { data: params_to_sign }, headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content'), 'Accept': 'application/json' }, success : function(signature, textStatus, xhr) { callback(signature); }, error : function(xhr, status, error) { /*handle error*/ } }); } const myWidget = window.cloudinary.createUploadWidget({ cloudName : '{{env('CLOUDINARY_CLOUD_NAME')}}', apiKey : '{{env('CLOUDINARY_API_KEY')}}', uploadPreset: 'ml_default', sources: [ 'local', 'url', 'image_search'], multiple: false, uploadSignature : generate_signature, }, (error, result) => { if (!error && result && result.event === "success") { console.log('Done! Here is the image info: ', result.info); $('#featured-image').attr('src', result.info.secure_url).removeClass("d-none"); } // console.log(error) } ) document.getElementById('upload_widget').addEventListener('click', () => myWidget.open(), false) </script>
Explanation:-
For signed upload cloudinary needs a signature. For that signature in this example we are using Laravel package.
uploadSignature : generate_signature,
Above code calls function generate_signature and which gets signature from BE
ate_signature = function( callback, params_to_sign ) { console.log(params_to_sign); $.ajax({ url : "/cloudinary/secret", type : "POST", dataType: "text", data : { data: params_to_sign }, headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content'), 'Accept': 'application/json' }, success : function(signature, textStatus, xhr) { callback(signature); }, error : function(xhr, status, error) { /*handle error*/ } }); }
Here is the BE code to generate signature
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Cloudinary\Api\ApiUtils; class CloudinaryController extends Controller { public function signRequest(Request $request) { $parameters = $request->all(); $parameters = $parameters['data']; $signature = ApiUtils::signParameters($parameters, env('CLOUDINARY_API_SECRET')); return response($signature, 200); } }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.