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
Related
My problem is that i upload a image on the website in laravel but the database save the path of my local storage with a strange name and extension:
The picture was uploaded fine in Storage/app/public but with another name (Like a hash code):
Now, how can get this name in /Storage/Public with a query on a database, or how can upload the image with the original name or by ID?
Code:
Form upload:
<form class="formulario" method="POST" enctype='multipart/form-data' action="{{ route('add_taller') }}">
#csrf
<h4>Añade el titulo correspondiente</h4><input name="titulo">
<h4>Añade un logo al taller</h4><input type="file" name="icono" class="taller_form {{ $errors->has('name') ? 'alert alert-danger' : ''}}" />
{!! $errors->first('image', '<p class="alerta">:message</p>') !!}
<h4>Añade una descripción</h4><textarea name="descripcion" rows="10" cols="50" value="{{ old('textarea') }}"></textarea>
{!! $errors->first('string', '<p class="alerta">:message</p>') !!}
<button type="submit">Subir a la web</button>
</form>
In controller:
public function add_taller(Request $request)
{
$request->file('icono')->store('public');
$user = Auth::user();
DB::table('talleres')->insert([
'icono' =>$request->icono,
'titulo' => $request->titulo,
'descripcion' => $request->descripcion,
'user_id' => $user->id,
'fecha'=> now()]);
return view('home');
}
View where I need to show the picture:
#foreach($datos as $dato)
<div class="taller">
<div>
<img src="{{Storage::url($dato->icono)}}" alt="" srcset="" class="icon_taller">
</div>
<div>
<h4>{{$dato->titulo}}</h4>
<p>{{$dato->descripcion}}</p>
</div>
<div class="botones_area">
<button>Descarga</button>
<button>Contacto</button>
</div>
</div>
#endforeach
As I can see, you don't save the path with the file extension.
When you use $request->file('icono')->store('public'); you generate a temporal file and the file extension is determined by Laravel with the MIME type.
What's about:
public function add_taller(Request $request)
{
$path = Storage::putFileAs(
'public', $request->file('icono'), Str::uuid()
);
$user = Auth::user();
DB::table('talleres')->insert([
'icono' => $path,
'titulo' => $request->titulo,
'descripcion' => $request->description,
'user_id' => $user->id,
'fecha'=> now()]
);
return view('home');
}
For the filename, I've used Str::uuid function to generate names with a different id. For store files, I've used Storage Laravel facade, take a quick look here: https://laravel.com/docs/8.x/filesystem#specifying-a-file-name
What do you think about these changes?
I tried to upload multiple images using validation system, even I upload the jpeg type images it gives me validation system error The images must be a file of type: jpeg, jpg, png, gif, svg.
register.blade.php
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group" id="divim">
<label>photos<span class="text-hightlight">*</span></label>
<input class="form-control" type="file" name="images[]" value="{{ old('images') }}" multiple>
#error('images')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</form>
RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
'images' => ['bail','required','mimes:jpeg,jpg,png,gif,svg','max:2048']
]);
}
method create/store
protected function create(array $data)
{
$dataim = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$namee = encrypt($file->getClientOriginalName()).'.'.$file->extension();
//$name = encrypt($namee).'.'.$file->extension();
$name = "profiles\\".$jdate->format('F').$jdate->year."\\".$namee;
$file->storeAs("public\\profiles\\".$jdate->format('F').$jdate->year, $namee);
//$Annonce->images = "annonces\\".$jdate->format('F').$jdate->year."\\".time().'.'.$image->extension();
array_push($dataim,$name);
}
}
$user->images=json_encode($dataim);
$imm =$user->images;
return User::create([
'images' => $imm
]);
}
Since you want to validate an array, you have to structure your rules differently:
return Validator::make($data, [
'images' => ['bail', 'required', 'array', 'min:1'],
'images.*' => ['bail', 'mimes:jpeg,jpg,png,gif,svg', 'max:2048'],
]);
See the docs on validating arrays for more information.
I m working on showing a post, when i post data with the image then my data stored in DB (image is also storing into destination folder) but not showing on the browser, here is the code of the page(index.blade.php) on which m trying to show post:
#extends('layouts.app')
#section('content')
<form method="POST" action="{{url('posts')}}" enctype="multipart/form-data">
<!--#if(session('message'))
{{session('messgae')}}
#endif-->
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
{{csrf_field()}}
Name:- <input type="text" name="title" value="{{old('title')}}">
Text:- <textarea name="body">value="{{old('body')}"></textarea>
Upload File:- <input type="file" name="thumbnail" value="{{old('thumbnail')}}">
<input type="submit" value="submit">
</form>
#endsection
this is post controller
public function store(Request $request)
{
if($request->hasFile('thumbnail') && $request->thumbnail->isValid())
{
$extension = $request->thumbnail->extension();
$filename = time()."_.".$extension;
$request->thumbnail->move(public_path('images'), $filename);
}
else
{
$filename = 'code.png';
}
\App\Post::create([
'title' => $request->title,
'body' => $request->body,
'thumbnail' => $filename,
]);
return redirect('posts');
}
I found a mistake in your code
#foreach($posts as post)
use
#foreach($posts as $post)
In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.
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'));
}