I'm using Laravel 5.2 and I want to make a form which can upload a pdf file with it. I want to add that file on folder "files" in "public" folder. here is my view:
<div class="form-group">
<label for="upload_file" class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input class="form-control" type="file" name="upload_file" id="upload_file">
</div>
</div>
and what should I do next? what should I add in my controller and route?
First you should add enctype="multipart/form-data" to your <form> tag. Then in your controller handle the file upload as follow:
class FileController extends Controller
{
// ...
public function upload(Request $request)
{
$uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension());
$request->get('upload_file')->move(public_path('files') . $uniqueFileName);
return redirect()->back()->with('success', 'File uploaded successfully.');
}
// ...
}
Link to Laravel Docs for Handling File Uploads
Laravel casts the file type params in request to UploadedFile objects. You can see Symfony's UploadedFile class here for available methods and attributes.
First of all, the documentation tells you exactly what to do here.
What you want to do is adding this to your <form> tag:
enctype="multipart/form-data" (This allows you to upload data), set a method(get/post) and an action (url).
Then you want to set up your routes.
For example:
Route::post('/pdf/upload', 'FileController#upload');
This way you make sure that when you send the form it will go to your FileController with upload as function.
In your controller you want to declare the file as explained in the docs.
$file = $request->file('photo');.
From this point you can do whatever you'd like to do with the file ($file). For example uploading it to your own server.
public function store(Request $request)
{
if($request->file('file'))
{
$file = $request->file('file');
$filename = time() . '.' . $request->file('file')->extension();
$filePath = public_path() . '/files/uploads/';
$file->move($filePath, $filename);
}
}
You Could Use Simple Method It Can Save The File
$path = $request->file('avatar')->store('avatars');
For More Information Here
you can this code for upload file in Laravel:
$request->file('upload_file')->move($path,$name);
You can take a look at how i upload files, all files are accepted:
first the code for the create.blade.php form
{!! Form::open(
array(
'url' => 'uploads',
'method' => 'post',
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true)) !!}
#include('uploadspanel.create_form')
{!! Form::close() !!}
Remember to set files to true
Then the uploadspanel.create_form
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('file', 'Bestand:') !!}
{!! Form::file('file',null,['class'=>'form-control']) !!}
</div>
#if(\Auth::user()->level == 2)
<div class="form-group">
{{ Form::label('approved', 'Beschikbaar voor:') }}
{{ Form::select('approved', array(1 => 'Iedereen', 2 => 'monteurs', 3 => 'concept'), null, ['class' => 'form-control']) }}
</div>
#else
{{ Form::hidden('approved', 3) }}
#endif
<div class="form-group">
{!! Form::submit('Bestanden uploaden',['class' => 'btn btn-primary form-control']) !!}
</div>
then the controller store function
public function store(UploadRequest $request){
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
Input::file('file')->move(
base_path().'/public/files/uploads/', $filename
);
if(\Auth::user()->level == 2) {
$approved = $request['approved'];
} else {
$approved = 3;
}
$fullPath = '/public/files/uploads/' . $filename;
$upload = new Uploads(array(
'name' => $request['name'],
'format' => $extension,
'path' => $fullPath,
'approved' => $approved,
));
$upload->save();
$uploads = Uploads::orderBy('approved')->get();
return view('uploadspanel.index', compact('uploads'));
}
Related
I want to upload a files to my laravel project. But I recognise that laravel randomly change my file name. How do I upload files to laravel without changing it's name. Also somehow my validation are not working. I just got redirected without any messages.
this are my blade
//show errors
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
/ul>
</div>
#endif
// forms
<form action="{{ route('designers.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group d-flex flex-column">
<label for="exampleInputFile">File input</label>
<input type="file" name="files[]" multiple>
</div>
<button type="submit">Submit</button>
</form>
this are my controller
$data = $request->validate([
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'file',
]);
if ($request->hasFile('files')) {
$allowedfileExtension=['pdf','jpg','png','docx','png','xlsx'];
$files = $request->file('files');
foreach ($files as $key => $value) {
$filename = $value->getClientOriginalName();
$extention = $value->getClientOriginalExtension();
$check = in_array($extention,$allowedfileExtension);
if ($check) {
File::create([
'name' => $value->store('designers','public'),
'type' => 'designer',
'project_id' => $data['project'],
'user_id' => Auth::user()->id,
]);
}
}
}
You can change your controller to this:
use Illuminate\Support\Facades\Storage;
function yourFunction(){
$this->validate($request,[
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'nullable|array|file|mimes:pdf,jpg,png,docx,xlsx' //This validates file and MIME type. Also if it is not required, it should perhaps be nullable.
]);
if($request->hasFile('files'){
$files = $request->file('files');
foreach($files as $file){
$filename = $file->getClientOriginalName();
Storage::disk('local')->put($filename, file_get_contents($file)); //This stores your file.
}
}
//Save stuff to DB here
}
Official doc on file storage: https://laravel.com/docs/5.8/filesystem
Official doc on Validation of MIME: https://laravel.com/docs/5.8/validation#rule-mimes
I am using Laravel 5.2 and I have two forms in different pages but same method and controller..
Both use public function store(Request $request){} method.
First Form in 'show.blade.php' page:
<form action="{{ url('projects') }}" name="comment_form" class="row" method="POST">
{{ csrf_field() }}
<div class="col-md-3">
<input placeholder="Name" name="name" type="text">
</div>
<div class="col-md-3">
<input placeholder="Email" name="email" type="text">
</div>
<div class="col-md-3">
<input placeholder="Subject" name="subject" type="text">
</div>
<div class="col-md-3">
<input value="Id Number : {{ $project -> id }}" name="project_id" type="text" readonly>
</div>
<div class="col-md-12">
<textarea placeholder="Comments" name="comments" cols="10" rows="10"></textarea>
</div>
<div class="col-md-12">
<input type="submit" value="Send Comments">
</div>
</form>
Second Form in 'create.blade.php' page:
{!! Form::open(array('route' => 'projects.store', 'files' => true, 'name' => 'project_form')) !!}
{{ Form::label('title', 'Title:', ['class' => 'top-bottom-margin']) }}
{{ Form::text('title', null, ['class' => 'form-control', 'maxlength' => '255']) }}
{{ Form::label('image', 'Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('image', ['accept' => 'image/*']) }}
{{ Form::label('second_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('second_image', ['accept' => 'image/*']) }}
{{ Form::label('third_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('third_image', ['accept' => 'image/*']) }}
{{ Form::label('body', 'Body:', ['class' => 'top-bottom-margin']) }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
{{ Form::submit('Create Project', ['class' => 'btn btn-success btn-lg btn-block top-bottom-margin']) }}
{!! Form::close() !!}
ProjectsController.php method code:
public function store(Request $request)
{
$data = $request->all();
if(isset($data['project_form'])){
// validation START
$this -> validate($request, array(
'title' => 'required | max:255',
'body' => 'required',
'image' => 'required'
));
// validation END
// storing in database
$project = new Project;
$project -> title = $request -> title;
$project -> body = $request -> body;
// First images START
$image = $request -> file('image');
$fileName = time() . '.' . $image -> getClientOriginalExtension();
$location = public_path('admin_images/' . $fileName);
Image::make($image) -> resize(860, 600) -> save($location);
//database store
$project -> image = $fileName;
//First images END
if ($request->hasFile('second_image')){
// second images START
$rand_number = rand(100, 2000);
$second_image = $request -> file('second_image');
$secondFileName = time() . $rand_number . '.' . $second_image -> getClientOriginalExtension();
$secondLocation = public_path('admin_images/' . $secondFileName);
Image::make($second_image) -> resize(860, 600) -> save($secondLocation);
//database store
$project -> second_image = $secondFileName;
// second images END
}
if ($request->hasFile('third_image')){
// third images START
$second_rand_number = rand(3000, 5000);
$third_image = $request -> file('third_image');
$thirdFileName = time() . $second_rand_number . '.' . $third_image -> getClientOriginalExtension();
$thirdLocation = public_path('admin_images/' . $thirdFileName);
Image::make($third_image) -> resize(860, 600) -> save($thirdLocation);
//database store
$project -> third_image = $thirdFileName;
// third images END
}
$project -> save();
Session::flash('success', 'Your project was created successfully!');
return redirect() -> route('projects.show', $project -> id);
}
Now I check if the comment_form is submitted or the project_form is submitted?
You can create hidden element to pass variable:
{!! Form::hidden('from', 'someView') !!}
And then get it in controller:
if ($request->from == 'someView') {
....
Also, you could pass variable by using sessions and by retrieving previous page URL, but I think hidden form element is the best choice when you're using form.
You could put a name and value to the submit button and check that.
if ($request->get('submit') == 'project') {
// do something
} elseif ($request->get('submit') == 'comment') {
// do something else
}
or use a switch
switch ($request->get('submit')) {
case 'project':
// do something
break;
case 'comment':
// do something else
break;
default:
// do this if above does not apply
break;
}
Picture 2 Form
Picture 3 Form
Hi,
I'm getting the error mentioned in the title when trying to upload a video using Laravel 5.2.
Images work correctly.
I've checked the PHP.ini settings of my MAMP server.
I'm using the form facade so I don't have to import token into my form.
I'm clueless, does anybody have suggestions what it might be?
<div class="container spark-screen">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Bestand uploaden</div>
<div class="panel-body">
{!! Form::open(
array(
'url' => 'uploads',
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true)) !!}
#include('uploadspanel.create_form')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
controller:
public function store(UploadRequest $request){
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
Input::file('file')->move(
base_path().'/public/files/uploads/', $filename
);
$approved = $request['approved'];
$fullPath = '/public/files/uploads/' . $filename;
$upload = new Uploads(array(
'name' => $request['name'],
'format' => $extension,
'path' => $fullPath,
'approved' => $approved,
));
$upload->save();
$uploads = Uploads::orderBy('approved')->get();
return view('uploadspanel.index', compact('uploads'));
}
Make sure you have the token included in your form, go to your page and inspect it, you should see something like this:
<input name="_token" type="hidden" value="Th4yqxNa3w3ooVAxRcSgvMug7ZEPA6BtaUw4qRck">
if you don't then add it in your blade like this:
{{ Form::hidden("_token", csrf_token()) }}
Another issue you might have is in case you are submitting this form through an AJAX request, in that case, you would need to pass the token there too:
$.ajax({
url : '{{ route("your_route", optional_parameter) }}',
type : "post",
data : { '_token' : '{{ csrf_token() }}', 'var1' : var1 },
}).done(...)
It had to do with MAMP settings. figured it out when i echo php_info();
then on line 6 or 7 followed the path to my php.ini
then changed the inputs again with another editor, saved it.
retart MAMP server
and done
This happens when your file which you are uploading is smaller than the max upload size but more than the POST_MAX_SIZE.
The input is truncated at the POST_MAX_SIZE which means that the csrf token is lost.
You can change these values in php.ini file.
I would like to design a form in Laravel which takes an image the User has selected, uploads it to the server and stores the image path in a 'image' field and also accepts a 'text' field which describes the image. I do not know how to store both the text field and image as an array to pass to the controller.
The Form
<div class="form-group">
{{ Form::label('description', trans('main.poster')) }}
{{ Form::text('description', Input::old('poster'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::file('image','files' => true) }}
</div>
<button type="submit" class="btn btn-success">{{ trans('dash.update') }}</button>
Controller
public function store()
{
$input = array('image' => Input::file('image'));
if ( ! $this->validator->setRules('image')->with($input)->passes())
{
return Redirect::back()->withErrors($this->validator->errors());
}
$this->title->uploadImage($input);
return Redirect::back()->withSuccess( trans('main.uploaded image success') );
Upload image
public function uploadImage(array $input)
{
$name = str_random(25);
$insert = array('image' => asset('assets/images/'.$name.'.jpg'), );
$this->images->saveTitleImage($input, $name);
}
Save image path
public function saveTitleImage($input, $name)
{
$encoded = Imagine::make($input['image']->getRealPath())
->encode('jpg');
Imagine::make($encoded)->save(public_path('assets/images/'.$name.'.jpg'));
}
I'm trying to make an image uploader, but it always give me this error
Call to a member function getClientOriginalName() on a non-object
here is my code controller code
public function uploadImageProcess(){
$destinatonPath = '';
$filename = '';
$file = Input::file('image');
$destinationPath = public_path().'/assets/images/';
$filename = str_random(6).'_'.$file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
if(Input::hasFile('image')){
$images = new Images;
$images->title = Input::get('title');
$images->path = '/assets/images/' . $filename;
$image->user_id = Auth::user()->id;
Session::flash('success_insert','<strong>Upload success</strong>');
return Redirect::to('user/dashboard');
}
}
and here is the upload form
<form role="form" action="{{URL::to('user/poster/upload_process')}}" method="post">
<label>Judul Poster</label>
<input class="form-control" type="text" name="title">
<label>Poster</label>
<input class="" type="file" name="image"><br/>
<input class="btn btn-primary" type="submit" >
</form>
what's wrong with my code?
You miss enctype attribute in your form markup.
Either do this
<form role="form" action="{{URL::to('user/poster/upload_process')}}" method="post" enctype="multipart/form-data">
...
</form>
or this...
{{ Form::open(array('url' => 'user/poster/upload_process', 'files' => true, 'method' => 'post')) }}
// ...
{{ Form::close() }}
These code are right, but you didn't check values of returns of Input::file('image'). I think returns value may be is not a correct object or your class Input does not have a public function name is getClientOriginalName.
Code:
$file = Input::file('image');
var_dump($file); // if return a correct object. you will check your class Input.
Good luck.
This is just because you forget to write enctype="multipart/form-data" in <form> tag.
This error happen just when you forget this:
<form class="form form-horizontal" method="post" action="{{ route('articles.store') }}" enctype="multipart/form-data">
Please Check Your Form 'files'=> true
{!! Form::open(['route' => ['Please Type Url'], 'class' => 'form-horizontal' , 'files' => true]) !!}
{!! Form::open(array('url' => '/xyz','files' => true)) !!}
{!! Form::close() !!}
if you are using Laravel Collective than you can try this solution
{{ Form::open(array('url' => 'user/poster/upload_process', 'files' => true, 'method' => 'post')) }}
{{ Form::close() }}
else if you are using html form tag than you have to put extra markdown for storing image data
<form class="form form-horizontal" method="post" action="{{ route('user/poster/upload_process') }}" enctype="multipart/form-data">