Laravel and FilePond sending chunks - php

Hi has anyone tried to use FilePond with Laravel to upload files in chunks ?
I am trying to do that but I dont know how to get the content of a PATCH method.
The upload starts, and a receive a bunch of PATCH methods, I see (Network Tab in Dev Mode Firefox) that they are different, because the offset changes.
Let me know if you need more details to help me.
My blade view (where the js is located):
<form action="{{ route('upload.store') }}" enctype="multipart/form-data"
method="post">
#csrf
<input class="" id="imageUploadFilePond" name="file" type="file">
<button class="btn btn-primary" type="submit">Submit</button>
</form>
#push('scripts')
<script src="https://unpkg.com/filepond#^4/dist/filepond.js"></script>
<script>
const inputElement = document.querySelector('#imageUploadFilePond');
const pond = FilePond.create(inputElement, {
server: {
url: '/upload',
patch: "/",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
},
chunkUploads: true,
chunkSize: 1048576,
chunkForce: true,
});
</script>
#endpush
In my UploadController.php my methods :
public function store(Request $request)
{
if ($request->file === '{}') {
return uniqid();
}
return '';
}
public function update(Request $request, $id)
{
$uploadOffset = $request->header('upload-offset');
$uploadLenght = $request->header('upload-length');
$uploadName = $request->header('upload-name');
$numberOfChunks = $uploadLenght / self::CHUNKSIZE;
$currentChunk = $uploadOffset / self::CHUNKSIZE;
return $id;
}

Related

how to send data from Blade view to controller in laravel to preform a post request

I am trying to favorite and unfavorite posts and insert it in favorites table if clicked and if clicked again it deletes it from favorites table i put my routes in web.php file
the functions in the controller which should be called in the route are not called i insert there dd() method to test it so i am guessing the problem is in the form action and not sending the data
<body>
...
#foreach ($posts as $post)
<div class="column">
#if ($post->showstar == true)
<form action="/favorites/delete" method="post">
<span class="foo fa fa-star checked"></span>
</form>
#endif
<h2>{{$post->title}}</h2>
<img src={{$post->url}} >
</div>
#endforeach
</body>
<script>
$(document).ready(function () {
$("form").on("click", ".foo", function () {
if ($(this).hasClass("checked")) {
$(this).removeClass("checked");
} else {
$(this).addClass("checked");
}
});
});
</script>
Controller:
class FavoritesController extends Controller
{
public function index()
{
return view('Favorites', ['favs' => Favorite::where('user_id', '1')->get()]);
}
public function view(Request $request)
{
dd("hello");
$fav = new Favorite();
$fav->user_id = $request->get('userid');
$fav->post_id = $request->get('postid');
$fav->save();
}
public function delete(Request $request)
{
dd("bye");
$fav = new Favorite();
$dfav = $fav->where('id', $request->id);
$dfav->delete();
return view('favorites');
}
public function fetch(Request $request)
{
$fav = new Favorite();
$favs = $fav->where('user_id', $request->user_id);
return view('favorites', compact('favs'));
}
}
Routes:
Route::post('/favorites', 'FavoritesController#view');
Route::post('/favorites/delete', 'FavoritesController#delete');
Route::post('/favorites/fetch', 'FavoritesController#fetch');
You could always try the plain and simple html form submit.
<form action="/favorites/delete" method="post">
#csrf
<input type="hidden" name="id" value="{{ $post->id }}">
<button>
<span class="foo fa fa-star checked"></span>
</button>
</form>
This way you can send the hidden input, post id in your case, to the controller and it will delete it.
You need a similar function ajax, to send data to a controller:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'youUrl',
data:{'youData':"YourValueData"},
type:'post',
success: function (response) {
alert(response);
},
error: function(x,xs,xt){
alert(x);
}
});

How to use both id and name in multiple image upload?

<input class="form-control" type="file" id="pro-image" name="image[]" multiple>
When Id work Successfully this time Name does not catch image path.
That means empty Array.
But when remove Id just use name="image[]" successfully submit value.
Assuming you have a form, you can submit the images via Ajax using the fetch API like so
<form action="/" method="post" enctype="multipart/form-data">
#csrf
<input class="form-control" type="file" id="pro-image" name="image[]" multiple>
<button type="submit">Submit</button>
</form>
<script>
let form = document.forms[0];
form.onsubmit = (event) => {
event.preventDefault();
fetch('/', {
method: 'POST',
credentials: "same-origin",
body: new FormData(form),
});
}
</script>
And return the paths array for the images like so
Route::post('/', function () {
$images = request()->file('image');
$paths = [];
foreach ($images as $image) {
$paths[] = $image->store('/public');
}
return $paths;
});
And without a form, listen to input change
<meta name="csrf-token" content="{{ csrf_token() }}">
<input class="form-control" type="file" id="pro-image" name="image[]" multiple onchange="submit()">
<script>
function submit() {
var ins = document.getElementById('pro-image').files.length;
var fd = new FormData();
for (var x = 0; x < ins; x++) {
fd.append("pro-image[]", document.getElementById('pro-image').files[x]);
}
fetch('/', {
headers: {
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
method: 'POST',
credentials: "same-origin",
body: fd,
});
}
</script>
And access from backend
Route::post('/', function () {
$images = request()->file('pro-image');
$paths = [];
foreach ($images as $image) {
$paths[] = $image->store('/public');
}
return $paths;
});
Now you can see paths of the stored images in public directory on the network tab of dev tools
Hope this helps

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Saving crop image with laravel

I started learning laravel, and attempt to make a website with it. I'm trying implement "uploading a crop image". I'm using croppie https://foliotek.github.io/Croppie/ and manage to successfully displaying on the browser.
Now, I want to save the image to the database. I'm struggling at this stage, I've spent hours searching and trying but it doesn't seem to work. I've read that laravel doesn't use the patch method to send crop images as well as I need ajax. Can someone help me how I would get the base64 from the form. This is my form:
<form action="{{route('program.updateImage', ['id'=> $program->id])}}" method="post" enctype="multipart/form-data">
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div id="crop" class="croppie-container">
</div>
<a class="upload-file">
<span>Upload</span>
<input type="file" name="image" id="upload"><br>
</a>
<br>
<input type="submit" name="submit" value="Save image">
</form>
This is my route:
Route::patch('program/image/{id}', 'ProgramController#updateImage')->name('program.update');
Code for croppie
$(function() {
var basic = $('#crop').croppie({
viewport: {
width: 400,
height: 200
},
boundary: { width: 400, height: 300 },
});
basic.croppie('bind', {
url: '{{asset('images/'.$program->image)}}'
});
});
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#crop').croppie('bind', {
url: e.target.result
});
}
reader.readAsDataURL(input.files[0]);
}
}
$('.upload-file input').on('change',function(){
readFile(this);
});
and my function:
public function updateImage(Request $request, $id){
//$this->validate($request, array('image' => 'mimes:jpeg,jpg,png'));
$program = Program::find($id);
//list($type, $data) = explode(';', $data);
//list(, $data) = explode(',', $data);
//$data = base64_decode($data);
echo $request;
}
Here jquery code for upload image
$('#crop_img_upload_button').on('click', function (e) {
var image_data = $('#crop').croppie('result', 'base64');
if (image_data != '') {
var formData = $('#crop_it_form').serialize();
$.ajax({
type: "POST",
url: "uploadUrl",
data: formData,
cache: false,
success: function (data)
{
//response here
}
});
} else {
// validation msg here
}
});
});
To get base64 of image use this :
var base64 = $('#crop').croppie('result', 'base64');

how to store image in database using laravel 5.3 by passing data with ajax in controller?

I've create one form which is given below
html code:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
ajax code:
function create()
{
alert();
var file = document.getElementById('file1');
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
var route = "http://localhost:8080/form";
console.log(FormData);
console.log(data1);
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});
}
This is my route :
Route::post('form', 'StoreController#newstore');
I've created controller which is given below
Controller :
public function newstore(Request $request)
{
$post = $request->file('data1');
dd($post);
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
when i run this code its show me this error :
MethodNotAllowedHttpException in RouteCollection.php line 218:
Try this:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
if for example your route is:
Route::post('form', 'yourcontroller#newstore');
JS
function create()
{
var file = document.getElementById('file1');
var route = "http://localhost:8000/form";
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
// we are using "$", i hope that you have jquery library
/* alternative you can do:
var getUpload = document.queryselector('#upload_form');
var data1 = getUpload[0];
*/
//if there is error try also console.log(formData)
// if error try console-log(data1); info about the file uploaded
// if error token verify console.log(token); have the token serial number
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});}
var submit = document.querySelector('#submit').onclick= create
CONTROLLER
public function newstore(Request $request)
{
$post = $request->file('data1');
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
Let me know if you get some error! i hope it work!

Categories