I am trying to build the controller that saves the image in my public folder using image intervention. I have used Cropit jquery plugin for image cropping and use ajax. The error " MethodNotAllowedHttpException in RouteCollection.php line 218" occurs.Below are my controller ,routes and view.
CropController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class CropController extends Controller
{
public function crop(Request $request){
$img = $request->image_data;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
Image::make($data)->save('images/images.jpg');
dd("image saved in images/images.jpg");
}
}
web.php
Route::get('/', function () {
return view('welcome');
});
Route::post('/image-crop',[
'uses'=>'CropController#crop',
'as'=>'image-crop',
]);
welcome.blade.php
<body>
<form method="post">
<input type="hidden" value="{{Session::token()}}" name="_token">
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="hidden" name="imagedata" class="hidden-image-data" />
<button type="submit">Submit</button>
</div>
</form>
<script>
var url1="{{route('image-crop')}}";
$(function() {
$('.image-editor').cropit();
$('form').submit(function() {
//event.preventDefault();
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$.ajax({
type:'post',
data:formValue,
url: '/image-crop',
success: function(data){
$('#result-data').text('New file in: images/'+data);
$('#crop').show();
}
})
.done(function(){
window.location.href=""+'/image-crop';
});
return true;
});
});
</script>
</body>
How to solve that error ?
Thank you
Hey Try to add this metatag on your layout
<meta name="csrf-token" content="{{ csrf_token() }}">
Also in your ajax request add this $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Let me know if it works!.
https://laravel.com/docs/5.1/routing#csrf-x-csrf-token
Related
I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.
this is my view :
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('body').on('click', '#saveBtn', function(){
var url;
var registerForm = $("#data-form");
var formData = registerForm.serialize();
$(this).html('saving...');
$('#saveBtn').attr('disabled',true);
$.ajax({
enctype: 'multipart/form-data',
url: '{{ route('blog.store') }}',
type:'POST',
data:formData,
success:function(data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Data');
}
});
});
});
</script>
and this is my controller
$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);
create.blade.php
#section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>
<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>
</form>
#endsection
#push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
#endpush
upload.js
$(function () {
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();
let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];
formData.append('photo', photo);
formData.append('name', name);
$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});
});
Controller
class MyController extends Controller
{
use StoreImageTrait;
public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}
StoreImageTrait
<?php
namespace App\Traits;
use Illuminate\Http\Request;
trait StoreImageTrait
{
public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready( function () {
$("form#data-form").on("submit",function (e) {
e.preventDefault();
var formData = new FormData(this);
//Ajax functionality here
$.ajax({
url : '{{route('blog.store')}}',
type : "post",
data : formData,
dataType : 'json',
success:function (data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
}, // success end
contentType: false,
processData: false
}); // ajax end
}); // form submit end
}); //document end
I have created a form where you can upload video files, but I notice that when uploading it, video takes time to upload depending on the size of the file,so to avoid people staring at a screen for a long time waiting for their video to upload I will send them to a page that says "Your video is processing and will be available when ready".The video is indeed saving to the public app folder and also it saves to my aws3 bucket folder as I requested but I noticed that its not saving the file in the database and I don't know why it by passes the database. I am using laravel, ffmpeg to convert and compress videos and ajax. Can someone help me with this. here is my code below
//this the fileupload.blade.php
<div class="container">
<div class="card">
<div class="card-body">
<form method="POST" action="{{ route('fileUploadPost') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input name="file" id="poster" type="file" class="form-control">
<input type="submit" value="Submit" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function validate(formData, jqForm, options) {
var form = jqForm[0];
if (!form.file.value) {
alert('File not found');
return false;
}
}
(function() {
$('form').ajaxForm({
uploadProgress: function(event, position, total, percentComplete) {
window.location.href = "complete";
},
success: function() {
},
complete: function(xhr) {
}
});
})();
</script>
//this is the controller
$request->validate([
'file' => 'required',
]);
$viddy=new Video;
$file = $request->file('file');
$fileName =uniqid().$file->getClientOriginalName();
$request->file->move(public_path('/app'), $fileName);
$name_file=uniqid().'video.mp4';
$ffp=FFMpeg::fromDisk('local')
->open($fileName)
->addFilter(function ($filters) {
$filters->resize(new \FFMpeg\Coordinate\Dimension(640, 480));
})
->export()
->toDisk('s3')
->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame'))
->save($name_file);
$imageName = Storage::disk('s3')->url($name_file);
$viddy->title=$imageName;
$viddy->save();
return response()->json(['success'=>'You have successfully upload file.']);
}
I'm trying to send data to back-end and i'm getting 404 error with this explanation in network tab:
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
Route
Route::middleware('verified')->group(function () {
Route::post('/snaptoken/{id}', 'Admin\PayController#token')->name('securepaymentnow');
});
Controller
public function token(Request $request, $id)
{
//Find project
$project = Project::findOrFail($id);
//rest of data
}
Blade
//form and button
<form id="payment-form" method="POST" action="{{route('securepaymentnow', $project->id)}}">
#csrf
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<button class="btn-sm bg-success pay-button" data-id="{{$project->id}}" type="submit"><i class="fas fa-fas fa-shield-alt"></i> Secure Payment</button>
//javascript
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/securepaymentnow")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
}
});
});
Any idea?
.........................................................................................................................
if you are using url() function, you should use the {{ url('/snaptoken') }}.
But if you want to use the "name" from the "securepaymentnow", use route() function with this example {{ route('securepaymentnow', $theId) }}.
Both should works.
Refer Laravel NamedRoute for details.
I am making a live search where user can search for business.
This would be done using ajax and display results however I get an error that there is an TokenMismatchException.
Here's my code:
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
Controller:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
Route::
Route::get('/', function () {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
Route::get('tfgm', 'GuzzleController#tfgm')->name('tfgm');;
Route::get('odeon', 'GuzzleController#odeon')->name('odeon');;
Route::get('chronicle', 'GuzzleController#oldham_chronicle')->name('chronicle');;
Route::get('smokeyard', 'GuzzleController#smokeyard')->name('smokeyard');;
Route::get('profile/', 'ProfileController#checkid')->name('profile');;
Route::get('create/business', 'BusinessController#addBusiness')->name('createBusiness');
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route::post('/searching/{search}', 'SearchController#search');
Route::post('update', 'ProfileController#updateProfile');
Route::post('create', 'BusinessController#createBusiness');
Route::post('image', 'ImageController#image');
Route::post('test2', 'ImageController#gallery');
Route::post('markers', 'BusinessController#saveMarkers');
Route::post('reviews', 'BusinessController#saveReviews');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/redirect/{provider}', 'SocialAuthController#redirect');
Route::get('/callback/{provider}', 'SocialAuthController#callback');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
#include('results')
</div>
</div>
</form>
Your line must be
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In your ajax code you have written X-CSRFToken that is wrong. Correct is X-CSRF-TOKEN
Always use below code in you script file
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Change X-CSRFToken to X-CSRF-TOKEN
Hello i use same script for Laravel 4.2 and Laravel 5.1 and problem is for Laravel 4.2 work perfectly, but on Laravel 5.1 i can't understand why it's return bad result
Problem is why I got $request->ajax() false for Laravel 5.1?
routes.php
Route::post('/upload-image', [
'as' => 'upload-image-post',
'uses' => 'PageController#profileImage'
]);
PageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PageController extends Controller
{
public function profileImage(Request $request)
{
//here is problem
//result good: (Laravel 4.2 shows true)
//result bad: (Laravel 5.1 shows false)
var_dump($request->ajax());
}
}
upload-image.blade.php (js)
<script>
jQuery(document).ready(function($) {
$('#upload_image').click(function(event) {
$('#image').trigger('click');
});
$('#image').change(function(event) {
/* Act on the event */
$('#imageform').submit();
});
$('#imageform').ajaxForm({
beforeSubmit: function() {
},
success: function(msg) {
},
error: function(request, status, error) {
},
complete: function(xhr) {
if(xhr.status != 401) {
$('#image').val('');
result = xhr.responseText;
result = $.parseJSON(result);
if( !$.isEmptyObject(result.file_base_url) ) {
var img = new Image();
img.onload = function() {
$('#register_profile_photo').attr('src', img.src);
$('#register_profile_photo').attr('alt', result.image_alt);
//spinner.stop();
$('#upload-image-error').text('');
}
img.src = result.file_base_url;
} else {
$('#upload-image-error').text(result.image[0]);
}
}
}
});
});
upload-image.blade.php (html)
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="{!! route('upload-image-post') !!}">
{!! csrf_field() !!}
<div style="display:none;">
<input type="file" name="image" id="image" placeholder="Please choose your image" >
</div>
</form>
<div class="profile-img">
<img style="float: right" id="register_profile_photo" src="default.png" alt="Default image">
<div style="float: right" class="img-edit">Edit picture</div>
</div>
PS. If you test for laravel 4.2 this code need change from "{!! .. !!}" to "{{ .. }}"
I do not think this problem is caused by Laravel version. Laravel sources show, that ajax() call is propagated to Symfony's request component. And that source changed good 5 years back.
You should trace if X-Requested-With header is sent to your application in both cases. You can also set breakpoint to Symfony\Component\HttpFoundation\Request::isXmlHttpRequest() and see what you have in headers.