image is not uploaded in Public/Storage/images in laravel - laravel

I want to upload an image and store in a folder. from my code, I am getting the name of the image but didn't save it in a folder. The path to store the image is:- /public/storage/images.What can I do?
Controller:-
if($req->hasFile('image'))
{
return $req->image->getClientOriginalName();
$path = $req->file('image')->store('/images');
}
View:-
<div class="form-group">
<label class="control-label col-sm-2" for="file">Image:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="file" placeholder="Choose photo" name="image">
</div>
</div>
Route:-
Route::view('Blog','pages.Blog');
Route::post('Blog','BlogController#Blogsinsertion');
Filesystem:-
'public' => [
'driver' => 'local',
'root' => 'storage/',
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],

public function Blogsinsertion(Request $request)
{
//.....
if ($request->hasFile('image')) {
$image = $request->file('image');
$name = time().rand(1, 99999) . '.' . $image->getClientOriginalExtension();
$Path = public_path('/storage/images');
$image->move($Path, $name);
//save name in db
//yourmodel->image = $name;
}
//........
}

I think your issue is caused because you are already returning before the store() call so the file is not actually saved.
Also, Laravel's documentation has instructions on a suggested way of setting up public disk so that everything can be neat in the storage folder by creating a symlink between /public/storage to /storage/app/public but you can change the location as needed. once you point the public disk in your filesystem config file to the new symlinked path then you can try the following code:
if($req->hasFile('image'))
{
// This line will save and then returns the saved file name
return $req->file('image')->store('/images','public');
}
If what you are trying to do is to save the uploaded file with the same name instead of the default hashed name then you can use the storeAs() method instead like so:
if($req->hasFile('image'))
{
$uploadedFile = $req->file('image');
// This line will save with same name and then returns the saved file name
return $uploadedFile->storeAs('/images', $uploadedFile->getClientOriginalName(),'public');
}

Related

How to display file in laravel-8

I can upload file in database
and it is stored in my upload files.
Now I want to display it in in my show.blade.php, so I did this, but it is not working.
<iframe src="/storage/uploads/{{ $file->file_path }}" width="400" height="400"></iframe>
as result I got this not found in show.blade.php
So how can I display it? This is my FileController.php
class FileUpload extends Controller
{
public function createForm(){
return view('file-upload');
}
public function fileUpload(Request $req){
$req->validate([
'file' => 'required'
]);
$fileModel = new File;
if($req->file()) {
$fileName = time().'_'.$req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time().'_'.$req->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
return back()
->with('success','File has been uploaded.')
->with('file', $fileName);
}
}
public function show(File $file)
{
// $news=News::find($id);
return view('show',compact('file'));
}
}
this is web.php
Route::get('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');
Route::get('/uploadshow', [FileUpload::class, 'show']);
Thanks
Screen short of ifream
You may use the URL method to get the URL for a given file. If you are using the local driver, this will typically just prepend /storage to the given path and return a relative URL to the file. If you are using the s3 driver, the fully qualified remote URL will be returned:
<iframe src="{{ URL::asset('storage/uploads/'.$file->file_path}}"width="400" height="400"></iframe>
You need to put proper path in iframe using asset()
<iframe src="{{ asset('storage/app/public/uploads/') }}/{{ $file->file_path }}" width="400" height="400"></iframe>
Your route uploadshow should have parameter fileId like this uploadshow/{fileId}.
Then in your show function will be show($fileID).
$file = File:find($fileID)
In your frame src,
asset($file->file_path)

error file could not be opened when upload image laravel

I am using Storage to upload multi photo to localhost. But I can't view the photo after upload. My orginal photo is 61Kb, but after upload, it is just 6 bytes.
In my Controller:
$img=array();
if($files=$req->images){
foreach($files as $file){
$name=date('Y-m-d-H:i:s')."-".$file;
Storage::disk('local')->put('public/product/'.$name, $file, 'public');
$img[]=$name;
}
}
ProductImage::insert( [
'id_detail' =>$ctsanpham->id,
'image'=> implode($img),
]);
View:
<input type="file" name="images[]" multiple="true" accept="image/png, image/jpg, image/jpeg">
Notification:
You want to use either of FilesystemAdapter::putFile or FilesystemAdapter::putFileAs when using an instance of Illuminate\Http\UploadedFile. e.g.
$options = ['visibility' => 'public'];
Storage::disk('local')
->putFileAs('public/product', $file, $name, $options);
If doing so using FilesystemAdapter::put, you need to first stream contents of the UploadedFile to string then put it.
FileSystemAdapter::putFileAs takes care of this for you.
I just solve my problem.
I forget putting method="post" in Form and method post in Route
Thank you all!

Laravel multiple file upload

I am trying to upload files (they can be any type), and I have a problem uploading file with certain way.
I am able to upload a file correctly using $request->file('file_name') and Storage::disk($disk)->put($path, $file);. However, $file parameter can only be through $request->file('file_name').
However, because of the way I want to upload multiple orders with multiple files like below:
Controller
foreach ( $filesArray as $key => $files ) {
$path = 'order/'.$order->id;
if ( isset($files[$i]) && !empty($files[$i]) ) {
for ( $j = 0; $j < count($files[$i]); $j++ ) {
$uploadedFile = FileHelper::upload($files[$i][$j], $path);
$orderFile = [];
$orderFile['order_id'] = $order->id;
$orderFile['file_id'] = $uploadedFile->id;
OrderFileModel::create($orderFile);
}
}
}
FileHelper
static public function upload($file, $path, $disk = 's3')
{
$fileOrm = new FileModel;
$fileOrm->size = $file->getSize();
$fileOrm->extension = $file->getExtension();
$fileOrm->bucket_name = self::$BUCKET_NAME;
$fileOrm->type = self::getFileType($file->getExtension());
$fileOrm->key = Storage::disk($disk)->put($path, $file);
$fileOrm->created_time = now();
$fileOrm->save();
return $fileOrm;
}
I've also attached images where I see the difference.
One with $request->file('file_name') and the other with just $request->file_name which is blob type.
The image below would return error saying fstat() expects parameter 1 to be resource, object given
How could I solve this problem?
Any advice or suggestion would be appreciated. Thank you.
Do you get your file list to use $request->files? If you do, change to $request->allFiles(). This method will convert File object to UploadedFile object.
Actually just put an array in your input file like this
<input type="file" name="files[]">
<input type="file" name="files[]">
<input type="file" name="files[]">
<input type="file" name="files[]">
NOTE: you need to enctype="multipart/form-data" enabled in your form.
Then in your controller, you can loop the input file by doing such
foreach($request->file('files') as $index => $file){
// do uploading like what you are doing in your single file.
}
Try:
$this->validate($request, [
'files.*' => 'file|mimes:...'
]);
foreach ($request->files as $file) {
$fileName = (string)Str::uuid() . '.' . $file->getClientOriginalExtension();
try {
if (\Storage::disk('s3')->put($fileName, file_get_contents($file))) {
FileModel::create([
'size' => '...',
'extension' => '...',
'bucket_name' => '...',
'type' => '...',
'key' => '...',
'created_time' => '...'
]);
}
} catch (\Exception $e) {
// ...
}
}
You might have been lucky before that some type casting on your $image object made a string out of it, I guess a simple chnage of your last line to
$disk->put($path, $file->__toString());
will fix the problem and is safer anyway as the "put" method officially only accepts strings (and looking at the implmentation also php resources). That should keep you compatible to changes in the long run.

Redirect error laravel

Hello i am using createProduct page for my create form. And after i created a product i want to redirect to the same page with parameters. Can you help me with the following error please ?
web.php
Route::get('/admin/products/create','productsController#createProduct');
Route::post('/admin/products/creating','productsController#creatingProduct');
creating function
public function creatingProduct(){
$product = new Product();
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->price = Input::get('price');
$categories = Category::all();
try {
$product->save();
$pageMessage = prepareMessage("alert-success","Yahoooo!!","Eklendiii");
} catch ( \Illuminate\Database\QueryException $e) {
$pageMessage = prepareMessage("alert-danger","Üzgünüz!!","Ürününüz eklenemedi");
}
// return view('admin.createProduct',compact('categories','pageMessage'));
return Redirect::route('/admin/products/create')->with( 'pageMessage', $pageMessage );
}
create function
public function createProduct(){
$categories = Category::all();
return view('admin.createProduct',compact('categories'));
}
createProduct.bladde.php
#if(isset($pageMessage))
{!!$pageMessage!!}
#endif
<form class="well form-horizontal" action=" {{url('admin/products/creating')}}" method="POST" id="contact_form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<!--{{ Form::open(['url' => '/admin/products/create', 'files' => true]) }}-->
<div class="form-group">
<label class="col-md-4 control-label">Ürün İsmi</label>
<div class="col-md-8 inputGroupContainer">
ERROR
InvalidArgumentException in UrlGenerator.php line 314:
Route [/admin/products/create] not defined.
You're passing a URL into Redirect::route() which expects the name of a route instead.
return redirect('/admin/products/create')->with( 'pageMessage', $pageMessage );
If you're using an older version of Laravel I believe it would be
return Redirect::to('/admin/products/create')->with( 'pageMessage', $pageMessage );
You can set up a named route and use that also, it's quite simple:
Route::post( '/admin/products/creating', [
'uses' => 'productsController#creatingProduct',
'as' => 'products.create'
]);
The benefits are that you can reference the route name throughout your application and if you decide to change the format of the URL you only have to do it in the one spot.
You should use route name instead of url if you're using route():
return redirect()->route('products.create');
So you can name your route:
Route::get('/admin/products/create', ['as' => 'products.create', 'uses' => 'productsController#createProduct']);
As alternative, you can use url like this:
return redirect('/admin/products/create');
You defined Redirect::route() which is not define you inside your route file.
It should be like below:
return Redirect::to('/admin/products/create')->with( 'pageMessage', $pageMessage );

I want to upload and save image in database but when i try to do it Call to a member function images() on null error shown up

I am beginner in laravel and i want to make image uploading and saving app.
Everything is going cool but as i try to upload images it isnot saved to database.
But in public/gallery/images folder images are present.How this is possible without saving in database.
When i try to upload following error shown up:
FatalErrorException in GalleryController.php line 71:
Call to a member function images() on null
My controller is:
public function doImageUpload(Request $request){
//get the file from the post request
$file = $request->file('file');
//set my file name
$filename = uniqid() . $file->getClientOriginalName();
//move the file to correct location
$file->move('gallery/images',$filename);
//save image details into the database
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
My view is:
<div class="row">
<div class="col-md-12">
<form action="{{url('image/do-upload')}}"
method="POST" enctype="multipart/form-data">
<label>Select image to upload:</label >
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
<input type="hidden" name="_token" value={{ csrf_token() }}>
</form>
</div>
and my image model is:
class Image extends Model
{
protected $fillable = [
'gallery_id','file_name','file_size','file_mime','file-path','created_by'
];
public function gallery(){
return $this->belongsTo('App\Gallery');
}
}
Being new to laravel i didnt get the actual error meaning Call to a member function images() on null??
How to fix this?
do a log debug on $gallery after you use the find method, there's a good chance it's not initialized, if the find method fails to find the id you've given it, it returns null
a good practice would be to verify you get an object back and verify your input contains gallery_id and that it is a number > 0
if ($request->has('gallery_id') && intval($request->input('gallery_id'))>0){
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
if ($gallery){
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
} else {
return Response::make('no gallery found with this $request->input('gallery_id') gallery_id',404);
}
} else {
return Response::make('invalid gallery_id as input',400);
}
you could also create the image via the Image create method as is instead of using the gallery relationship, that would have created an image probably with the gallery_id of 0 if the galley_id input is incorrect.
$image = Image::create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
I don't know if you resolved the problem, but I had the same issue and I found the solution.
When you send a form, you need to put a hidden input .
<input type"hidden" name="gallery_id" value="{{ $gallery->id }}">
I'm sure you work on the same project as me, DropZone Gallery, if so I think you have the solution

Resources