Cannot upload images laravel - laravel

I uploaded my files on my server, but I cannot change my root folder to public via the hosting company, so I moved the files from public to the httpdocs directory, but I have now an issue with uploading images, i made this path
$this->validate($request, [
'image' => 'image|nullable|max:1999'
]);
if ($request->hasFile('image')) {
$filenameWithExt = $request->file('image')->getClientOriginalExtension();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . Carbon::today()->toDateString() . '.' . $extension;
$request->file('image')->storeAs('/../Supplier/public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
And when I submit my form I get this error
Path is outside of the defined root, path:
And to show the image after upload i have this code in html
<td><a download="retourmelding_{{$retour->firmaname}}" href="/storage/images/{{$retour->images}}" title="Foto">
<img alt="Foto" src="/storage/images/{{$retour->images}}">
</a></td>
But locally it works perfectly

Please try it:
$request->file('image')->storeAs(storage_path('images'), $fileNameToStore);
The directory definition you have made is incorrect.
../httpdocs/storage/images/ mean is [laravel directory]/httpdocs/storage/images/
Use helpers for directory defination: Helpers - Laravel

I would change the disk in "config \ filesystems.php" and put something like this:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],

You can do that using the below code:
In config/filesystem.php
'my_file' => [
'driver' => 'local',
'root' => storage_path(),
],
In controller
$fileNameToStore = $request->file('myfile');
$name = $fileNameToStore->getClientOriginalName();
Storage::disk('my_file')->PutFileAs('images', $fileNameToStore, $name);
For retrieving the image in view file using the route. Because of directly can not access the storage/images folder.
You need to create a new function in the controller.
use Auth, Storage, File, Response;
public function displayImage($filename)
{
$path = storage_path('images/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
New Route add
Route::get('image/{filename}', 'YOURCONTROLLER#displayImage')->name('image.displayImage');
View( Retrieving image)
<img src="{{ route('image.displayImage',$image) }}" alt="" title="">

Related

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.
You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

Laravel server, upload to public_html rather than upload in project folder

I've been trying surfing around this site looking for answers, but nothing works for me, i want to upload an image that save in public_html folder, instead of saving it in project folder (i seperate the project folder and put all public file in public_html folder). Already bind the public.path but it returns to my project folder, not public_html one.
My image upload controller
public static function uploadSubmit($request, $type, $for)
{
if($request->hasFile('photos'))
{
$allowedfileExtension=['jpg','png'];
$files = $request->file('photos');
foreach($files as $file)
{
$extension = $file->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
//dd($check);
if($check)
{
$idx = Image::create([
'type' => $type,
'ids' => $for,
'ext' => $extension,
])->id;
$filename = $idx . '.' . $file->getClientOriginalExtension();
$filename = $file->storeAs(public_path('images/'), $filename);
}
}
}
}
i already do the public path bind like this in public_html/index.php
$app->bind('path.public', function() {
return __DIR__;
});
Thank you!
First, add config to filesystem.php on config folder:
'disks' => [
...
'public_html' => [
'driver' => 'local',
'root' => public_path(),
'visibility' => 'public',
],
...
],
Second, store image with code:
$file->storeAs('images', $filename, 'public_html')
P/S: Remember to configure the correct path for the public_html directory:
$app->bind('path.public', function(){
return __DIR__.'/../../public_html';
});
The public disk is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public.
When using the local driver, all file operations are relative to the root directory defined in your filesystems configuration file. By default, this value is set to the storage/app directory. Therefore, the following method would store a file in storage/app/file.txt:
Storage::disk('local')->put('file.txt', 'Contents');
Or in your case in storage/app/images/file.txt
$file->storeAs(public_path('images/'), $filename);
You can change where these files are stored by changing the filesystems configuration file.
'local' => [
'driver' => 'local',
'root' => public_path(),
],

move uploaded file to root/public_html

i have a laravel project and its uploaded on a sharing host
i have this code for moving uploaded file to folder :
$request->file->move(public_path('images\banners'), $new_name);
my website is like :
root/
laravel
public_html
i just want to move uploaded file to public_html folder
public function register()
{
//
$this->app->bind('path.public', function() {
return realpath(base_path().'/../public_html');
});
}
i try this but its not working
The laravel way is to use FlySystem. Open up config/filesystems.php and add a new entry for public_html.
'disks' => [
'public_html' => [
'driver' => 'local',
'root' => '/full/path/to/public_html',
],
...
Then use it as Storage::disk('public_html')->put('filename', 'contents');. There are other methods on the docs on how to move or upload files to a specific storage here https://laravel.com/docs/5.8/filesystem.
Additionally, instead of specifying the fullpath you can use helper functions such as storage_path() or public_path() depending on where your directory is.
$file = $request->file('image');
$extension = $file->getClientOriginalExtension(); // getting image extension
$filename =time().'.'.$extension;
$path = $file->move(public_path('uploads'), $filename);
$newPath = explode('\public\\', $path);
$filePath = end($newPath);

Cannot fetch image from storage directory in laravel

The image is not shown when I display it in the index page.
My view file (index.blade.php):
<div class="row">
#if(App\News::count() > 0)
#foreach($news as $n)
<div class="col-md-8 panel border-right">
<br />
<img src="{{ asset('storage/images/news/'. $n->image) }}" width="200px" height="100px">
--$n->image returns News_1.jpg which is the image name stored in the storage directory.
<h1>First Div</h1>
</div>
#endforeach
#endif
<div class="col-md-4">
<h1>Second Div</h1>
</div>
</div>
My controller:
public function store(Request $request)
{
$this->validate($request,
[
'head' => 'required|max:191',
'title' => 'required|max:191',
'body' => 'required',
'pic' => 'required'
]);
$filename="";
$extension="";
if($request->hasFile('pic'))
{
if((News::orderBy('id', 'desc')->first()) != null)
{
$id = ((News::orderBy('id', 'desc')->first()->id)+1);
$filename = "News_" . $id;
}
else
{
$filename = "News_" . 1;
}
$extension = $request->pic->getClientOriginalExtension();
$filename = $filename . "." . $extension;
//return $request->pic->getClientOriginalName();
$request->pic->storeAs('public/images/news', $filename);
}
else
{
return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid file.']);
}
$news = new News;
$news->head = $request->head;
$news->title = $request->title;
$news->body = $request->body;
$news->image = $filename;
$news->save();
Session::flash('success', 'The record was successfully saved.');
return redirect()->route('news.index');
}
I have already linked the storage directory with the public directory:
My directory structure:
The images are stored properly in both the Application and database but it cannot be displayed properly, when I run the app, I get the following view:
When open the image in new tab, I see the following address bar:
This is the local driver configuration:
Any help is appreciated in advance.
If your current route is /cricket and you reference an image with 'storage/images/news/news1.jpg' then the web browser is going to assume that this image is relative to the cricket resource.
Your image src needs to start with either the full URL or a / to indicate it is relative to the root folder
In this case I would hard code the URL since you have hard coded it in the asset helper anyway
<img src="/storage/images/news/{{ $n->image }}"
You can try setting your local driver to something like this:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],

How to use Redactor image upload in laravel 4?

I am trying to use Redactor with Laravel4. I can succesfully edit my textarea but I cant get to work with image uploads. When I try to upload a file I get 500 error and In developer tools , I can see
Request URL:http://projemiz.dev/admin/blogs/3/postimage/3
This is my link for redactor photo upload:
<script>$('#editor').redactor({ imageUpload: "postimage/{{$post->id}}"});</script>
My routes are inside prefixes :
# Blog Management
Route::group(array('prefix' => 'blogs'), function()
{
Route::get('/', array('as' => 'blogs', 'uses' => 'Controllers\Admin\BlogsController#getIndex'));
Route::get('create', array('as' => 'create/blog', 'uses' => 'Controllers\Admin\BlogsController#getCreate'));
Route::post('create', 'Controllers\Admin\BlogsController#postCreate');
Route::get('{blogId}/edit', array('as' => 'update/blog', 'uses' => 'Controllers\Admin\BlogsController#getEdit'));
Route::post('{blogId}/edit', 'Controllers\Admin\BlogsController#postEdit');
Route::post('{blogId}/postimage','Controllers\Admin\BlogsController#postImage');
Route::get('{blogId}/delete', array('as' => 'delete/blog', 'uses' => 'Controllers\Admin\BlogsController#getDelete'));
});
and my controller is :
public function postImage($blogId) {
$path = base_path().'/public/uploads/img/posts/' . (int)$blogId;
$image = Input::file('photo');
if (Input::hasFile('photo'))
{
$fileName = $file->getClientOriginalName();
$image->move($path,$fileName);
$image = new Image;
$image->name = $fileName.name;
$image->save();
// resizing an uploaded file
Image::make($image->getRealPath())->resize(300, 200)->save($path.'thumb-'.$fileName);
Image::make($image->getRealPath())->resize(300, 200)->save($path.'thumb-'.$fileName);
//File::delete( $path . '/' . Input::file('file.name'));*/
}
}
Can anyone help me to fix my link inside redactor?
Try changing your js-script this:
<script>$('#editor').redactor({ imageUpload: "/{{$post->id}}/postimage"});</script>
In the upload function return the path of the image after upload
public function postImage($blogId)
{
$path = base_path().'/public/uploads/img/posts/' . (int)$blogId;
$image = Input::file('photo');
if (Input::hasFile('photo'))
{
$fileName = $file->getClientOriginalName();
$image->move($path,$fileName);
$image = new Image;
$image->name = $fileName.name;
$image->save();
// resizing an uploaded file
Image::make($image->getRealPath())->resize(300, 200)->save($path.'thumb-'.$fileName);
Image::make($image->getRealPath())->resize(300, 200)->save($path.'thumb-'.$fileName);
// Return Image path as JSON
if ($file->move($path, $fileName))
{
return Response::json(array('filelink' => $path . '/' . $fileName));
}
}
}

Resources