error file could not be opened when upload image laravel - 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!

Related

How to redirect back to preivous template with both input and collections of Eloquent in Laravel?

I need to pass both input and collections, that this controller produce, to the previous template. I try to use:
return redirect()->back->withInput()->with('userdata',$userdata);
but get undefined variable when access $userdata in template. This is controller:
public function inquireUpdateProcess(){
$input = request()->all();
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
return redirect()->back->withInput()->with('userdata',$userdata);
}
And this is template of view:
<label for="text-authority-change">name of authority:</label>
<input type="text" name="authority_name_change" class="form-control"
value="{{$userdata->authority_name}}" />
I use the following instead then it works. But the outcome is couldn't pass the input data and collection in the same time, I know there must be a way to use return redirect()->back()... and get both previous input and the collection in template.
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
$binding = [
'title' => 'Authority management',
'userdata' => $userdata,
];
return view('authority.authView', $binding);
I found out the data put into with() can only get it by session in template of blade like this :
<input type="text" id="text-authority-change" name="authority_name_change" class="form-control"
value="{{session()->get('userdata')['authority_name']}}"
/>
Even the collections of Eloquent are the the same way to access.

image is not uploaded in Public/Storage/images in 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');
}

laravel local storage 404 error on images

I have made a youtube style website, some people may click the video to be private, I keep these videos in storage/app/vidoes/{channelname}, the public images and videos I have working not a problem but local storage I am having a problem with, any ideas?
just getting a 404 on the thumbnails
thanks
view
<img src="{{ route('home.image', ['file_path' => 'videos/' . $video->channel_name . '/thumbnails/' . $video->video_thumbnail_name]) }}" alt="" class="img-responsive">
route
Route::get('{file_path}', [
'uses' => 'HomeController#getImage',
'as' => 'home.image'
]);
controller
public function getImage($filepath)
{
$fileContents = \Storage::disk('local')->get($filepath);
$response = \Response::make($fileContents, 200);
$response->header('Content-Type', "image/jpg");
return $response;
}
Laravel 5.8 local storage working for images
view
<img class="home-video" src="{{ route('getImage', ['thumbnail' => $video->video_thumbnail_name, 'channel_name' => $video->channel_name]) }}" alt="" >
Route
Route::get('get-image/{channel_name}/{thumbnail}','HomeController#getImage')->name('getImage');
Controller
public function getImage($channel_name,$thumbnail)
{
$fileContents = \Storage::disk('local')->get("videos/$channel_name/thumbnails/$thumbnail");
return \Image::make($fileContents)->response();
}
see how the thumbnail is important for me, I was passing the thumbnail name eg photo.jpg if you are using route model binding you would want to pass the id of the image, hope this saves someone a few hours

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.

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