In my laravel 5.2 project I need to create a multi file upload area. I choose Dropzone.js
Now my problem is how to use this plugin with laravel.
this is my view:
<div class="tab-pane" id="tab_2">
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Facebook:</label>
<div class="col-sm-10">
<input type="text" name="facebook" class="form-control">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Twitter:</label>
<div class="col-sm-10">
<input type="text" name="twitter" class="form-control">
</div>
</div>
<div class="form-group">
<label for="video" class="col-sm-2 control-label">Video:</label>
<div class="col-sm-10">
<input type="text" name="video" class="form-control">
</div>
</div>
<!--File Upload-->
<div class="dropzone" id="dropzoneFileUpload">
</div>
<script type="text/javascript">
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::getToken() }}";
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzoneFileUpload", {
url: baseUrl+"/dropzone/uploadFiles",
params: {
_token: token
}
});
Dropzone.options.myAwesomeDropzone = {
paramName: "file",
maxFilesize: 2, // MB
addRemoveLinks: true,
accept: function(file, done) {
},
};
</script>
my controller:
public function store(SpotFormRequest $request) {
$user = Auth::user();
$role = $user->role;
if($role === 'manager'){
$idagent = 1;
$idmanager = $user->id;
}
else{
$idagent=$user->id;
$idmanager=0;
}
$spot = new Spot(array(
'agent_id'=>$idagent,
'manager_id'=>$idmanager,
'name' => $request->get('spotname'),
'address' => $request->get('address'),
'zip' => $request->get('zip'),
'city'=>$request->get('city_id'),
'phone' => $request->get('phone'),
'mobile' => $request->get('mobile'),
));
$spot->save();
return redirect('/administrator/spot-new')->with('status', 'Your spot has been created!');
}
I need to integrate the upload in the controller.
Implementing Dropzone in Laravel project could be a bit tricky
This is a step by step tutorial which I found extremely helpful
This tutorial covers:
Auto image upload
Remove images directly from Dropzone preview with AJAX request
Image counter for uploaded images
Saving images as full size and icon size versions Using
Image Intervention package for resizing and image encoding
Saving image data to database
Unique filenames for images on server side
Related
I currently have an edit page, which hits an update function to update the Itinerary object when changed.
On this page, if I click submit straight away, and dd() the $request from the ItineraryController, it returns all of the existing form data, as expected.
If I edit the data in the fields, then submit it, it returns successfully with a full request object as expected.
If, however, I choose a file in the "replace file" selector, the entire request object shows as null when the form is submitted, and thus can't be submitted.
How can I adjust this so that the "replace file" input is operational, and fills the request object with the existing itinerary data?
Component:
<template>
<form #submit.prevent="submit">
<div class="row w-75 m-auto">
<h1>Edit Itinerary</h1>
<div class="col-md-6">
<label for="title">Title</label>
<input v-model="form.title" class="form-control" name="title" placeholder="Itinerary Title" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="gen_narrative">Narrative</label>
<textarea v-model="form.gen_narrative" class="form-control" name="gen_narrative" placeholder="Itinerary Narrative"></textarea>
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label>Current Photo</label>
<img :src="assetUrl(props.itinerary.f_photo)" alt="featured photo" />
</div>
</div>
<br />
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="fileChange" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="authorid">Author Name</label>
<input v-model="form.authorid" class="form-control" name="authorid" placeholder="Author Name" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<button class="btn btn-primary" type="submit">Edit Itinerary</button>
</div>
</div>
</form>
</template>
<script setup>
import { useForm } from "#inertiajs/inertia-vue3";
function assetUrl(path) {
return process.env.MIX_BASE_URL + "storage/" + path;
}
function fileChange(event) {
form.f_photo = event.target.files[0];
}
let props = defineProps({
itinerary: {
type: Object,
required: true,
},
});
let form = useForm({
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops,
});
let submit = () => {
console.log(form.title);
form.patch("/itineraries/" + props.itinerary.id);
form.reset();
};
console.log(form);
</script>
<style scoped></style>
Controller:
public function edit($id)
{
$itinerary = Itinerary::find($id);
return Inertia::render('Itineraries/Edit', [
'itinerary' => $itinerary,
]);
}
public function update(Request $request, $id)
{
$itinerary = Itinerary::find($id);
$itinerary->title = $request->title;
$itinerary->gen_narrative = $request->gen_narrative;
//upload the photo
if ($request->hasFile('f_photo')) {
$itinerary->f_photo = $request->f_photo->store('public/itinerary_photos');
}
$itinerary->authorid = $request->authorid;
$itinerary->save();
return redirect('/itineraries');
}
let form = useForm({
forceFormData: true,
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops
})
The best I can come up with is writing your file upload inline
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="form.f_photo = event.target.files[0]"/>
</div>
</div>
Based on this example in official documentation you can do
<input type="file" #input="form.f_photo = $event.target.files[0]" />
Your issue is probably because Inertia does not natively support uploading files using a multipart/form-data request for the put, patch or delete methods, as is stated here (in the "Multipart limitations" section).
An alternative way is to submit without form helper using post method with the _method attribute of 'put', like:
Inertia.post("/itineraries/" + props.itinerary.id", {
_method: 'put',
f_photo: form.f_photo,
})
I tried to upload an image into the form using ajax method, here the my form code in blade file:
<form action="#" id="form" enctype='multipart/form-data' class="form-horizontal">
{{ csrf_field() }}
<div class="modal-header">
<h4 class="modal-title">Data Form</h4>
</div>
<div class="modal-body">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-4">Description</label>
<div class="col-md-8">
<input name="description" id="description" class="form-control" type="textarea">
<small class="errorDescription hidden alert-danger"></small>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Price</label>
<div class="col-md-8">
<input name="price" id="price" class="form-control" type="number">
<small class="errorPrice hidden alert-danger"></small>
</div>
</div>
<div class="form-group">
<input type="file" name="image" id="image">
</div>
</div>
</div>
</form>
And the Ajax POST method is:
function save()
{
var url;
url = "{{ URL::route('editor.data-wh.store') }}";
$.ajax({
type: 'POST',
url: url,
data: {
'description': $('#description').val(),
'price': $('#price').val(),
'image': $('#image').val()
},
success: function(data) {
console.log(data);
}
}
}
And here my controller:
public function store(Request $request){
// if request has file
if($request->hasFile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension=$request->file('image')->getClientOriginalExtension();
$fileNameToStore= date('mdYHis') . uniqid() .$filename.'.'.$extension;
request()->image->move(public_path('img'), $fileNameToStore);
}else{
$fileNameToStore='no-image.jpeg';
}
$post = new WhData();
$post->description = $request->description;
$post->price = $request->price;
$post->image=$fileNameToStore;
$post->save();
return redirect()->back();
}
But the data never save the uploaded image to the DB, the Database always stored no-image.jpeg (my else condition in controller) for image value. Here my form request in the Header request data in browser console:
description: Watermelon
price: 45
image: C:\fakepath\thumbnail.jpg
Almost 3 days now to solved this and look over the net too, but still no luck. Any idea how to solved this?
Thanks,
You could just change the data with data:new FormData(document.getElementById('form'));
This way you can send binary files (files) to the server.
I used intervention image to resize image for a laravel 6 app. After developing on local server, which worked perfectly, i try uploading to a shared hosting, but i am getting errors.
Image source not readable
I have tried everything i saw on stackoverflow, and laracast. but they are not working for me.
i try
changing the base path in index.html
Running storage link, in Appserviceprovider
removing public_html(). worked but not saving image to public_html->storage folder
dd() the request paths, its correct
my codes:
index.php:
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$app->bind('path.public', function() {
return __DIR__;
});
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$app->bind('path.public', function() {
return __DIR__;
});
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
Post Controller that handles image uploads
$image = $request->file('image');
$imagePath = $image->store('posts', 'public');
$image = Image::make(public_path($request->file('image')->getRealPath()))->fit(1263, 864);
return $image;
$image->save();
BlogPost::create([
'title' => $request->title,
'image' => $imagePath,
'categories' => json_encode($request->categories),
'isEvent' => $request->isEvent,
'isEditorial' => $request->isEditorial,
'body' => $request->body,
]);
<form enctype="multipart/form-data" action="{{ route('post.store')}}" method="POST">
<div class="container">
#method('post')
#csrf
<div class="col-md-12">
<div class="card card-outline card-info">
<div class="card-body pad">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add blog post</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="form-group">
<label for="customFile">Post Title</label>
<input type="text" class="form-control" name="title" id="title" maxlength="250">
<small id="character_txt" class="text-success"><span id="characters">255</span> characters left</small>
</div>
</div>
<div class="col-sm-12 col-md-6">
<label for="customFile">Upload Post image</label>
<div class="input-group input-group-md">
<input type="file" name="image" class="form-control">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
The Image source not readable is pointing to the make(). i have confirm the image path has the correct path.
Error page
I was having the same problem with Intervention and Laravel 6. After lots of research that never helped me, I did the following and it worked.
Delete the storage link folder inside public
Launch a terminal in your cpanel, cd to your project and run php artisan storage:link
I then tried uploading once again and it worked just fine
I'm new in CI. I just created login form in CI, Every first time I open my browser and login to the form it doesn't redirect to the page according to the action even the password & user are correct. it's only refresh the page. but the second time I do the login, it works fine.
I have trying with different browser and using incognito doesn't help either. So the error only occurs the first time I running the script.
any ideas?
Thanks
here's the view:
< script type = "text/javascript" >
$(function() {
$("#login_form").submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function(o) {
if (o.result === 1) {
window.location.href = '<?=site_url('
dashboard ')?>';
} else {
alert('Invalid login');
}
}, 'json');
});
}); <
/script>
<div class="row">
<div class="span6">
<form id="login_form" class="form-horizontal" method="post" action="<?=site_url('api/login')?>">
<div class="control-group">
<label class="control-label">Login</label>
<div class="controls">
<input type="text" name="login" class="input-xlarge" />
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input type="password" name="password" class="input-xlarge" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Login" class="btn btn-primary btn-lg btn-block" />
</div>
</div>
</form>
</div>
</div>
And here's my controller:
<?php
public function login()
{
$login = $this->input->post('login');
$password = $this->input->post('password');
$this->load->model('user_model');
$result = $this->user_model->get([
'login' => $login,
'password' => hash('sha256', $password . PASX)
]);
$this->output->set_content_type('application_json');
if ($result){
$this->session->set_userdata(['user_id' => $result[0]['user_id']]);
$this->output->set_output(json_encode(['result' => 1]));
return false;
}
$this->output->set_output(json_encode(['result' => 0]));
}
I have an application built in Laravel 4 and uses this package
I am following this tutorial
This is the error I am getting http://postimg.org/image/c4qwjysgp/
My issue is $token is not correctly passing or the $token is empty.
I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing.
Here is the view
#extends('layouts.main')
#section('content')
<h1>Your Order</h1>
<h2>{{ $download->name }}</h2>
<p>£{{ ($download->price/100) }}</p>
<form action="" method="POST" id="payment-form" role="form">
<input type="hidden" name="did" value="{{ $download->id }}" />
<div class="payment-errors alert alert-danger" style="display:none;"></div>
<div class="form-group">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>Expires</span>
</label>
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" />
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" />
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Submit Payment</button>
</div>
</form>
#stop
Here is the route
Route::post('/buy/{id}', function($id)
{
Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key'));
$download = Download::find($id);
//stripeToken is form name, injected into form by js
$token = Input::get('stripeToken');
//var_dump($token);
// Charge the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $download->price,
"currency" => "gbp",
"card" => $token,
"description" => 'Order: ' . $download->name)
);
// If we get this far, we've charged the user successfully
Session::put('purchased_download_id', $download->id);
return Redirect::to('confirmed');
} catch(Stripe_CardError $e) {
// Payment failed
return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.');
}
});
Here is the js
$(function () {
console.log('setting up pay form');
$('#payment-form').submit(function(e) {
var $form = $(this);
$form.find('.payment-errors').hide();
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message).show();
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.get(0).submit();
}
}
Here is the stripe.php in package
<?php
return array(
'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO',
'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG'
);
Seems like the Config::get might be wrong.
It would have to be written this way.
Stripe::setApiKey(Config::get('stripe.api_key'));
I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.