Case: Uploading avatars. This is working offline on my localhost, but after putting it online to 000webhost hosting provider, this does not work anymore. The file is NOT being uploaded but Laravel does not returns any error. Any idea to solve this?Thankyou.
This is my controller:
if ($request->hasFile('avatar'))
{
$user = User::find(Auth::user()->id);
$avatar = $request->file('avatar'); // in here
$filename = time() . '.' . $avatar->getClientOriginalName();
$path = base_path();
$path = str_replace("gsm-cp","public_html",$path);
$destinationPath = $path.'/img/avatars';
$avatar->move($destinationPath, $filename);
$user->avatar = $filename;
$user->save();
}
This is my config/filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
...
You can simplify your code by using storeAs(), as well as replacing $user = User::find(Auth::user()->id); with $user = Auth::user();.
storeAs() takes a path, the filename to store, and takes an optional array, which can for example specify the disk -- here, we're using the public one. This would store the images in ./storage/app/public/avatars/1597750757_1.jpg for user with ID 1.
if ($request->hasFile('avatar'))
{
$user = Auth::user();
$avatar = $request->file('avatar');
$filename = time().'_'.$user->id.'.'.$file->getClientOriginalExtension();
$path = $avatar->storeAs("/avatars/", $filename, ['disk' => 'public']);
$user->avatar = $filename;
$user->save();
}
You may alternatively want to store down the path, and not just the filename. The storeAs() method returns the full path to the image (including its name).
File Storage docs
Related
I am trying to upload a file to a public folder which was working lately but now it is showing below error:
Disk [public] does not have a configured driver.
I tried checking for configured driver in config/filesystems.php but, it is already set there. I am not getting where the issue might be.
Upload code:
public function upload(ProductImageRequest $request, Product $product)
{
$image = $request->file('file');
$dbPath = $image->storePublicly('uploads/catalog/'.$product->id, 'public');
if ($product->images === null || $product->images->count() === 0) {
$imageModel = $product->images()->create(
['path' => $dbPath,
'is_main_image' => 1, ]
);
} else {
$imageModel = $product->images()->create(['path' => $dbPath]);
}
return response()->json(['image' => $imageModel]);
}
Code in config/filesystems.php
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
i use this code for moving the picture and storing its name you may want to give it a shot
//get icon path and moving it
$iconName = time().'.'.request()->icon->getClientOriginalExtension();
$icon_path = '/category/icon/'.$iconName;
request()->icon->move(public_path('/category/icon/'), $iconName);
$category->icon = $icon_path;
i usually move the image then store its path in db and this is what my code shows you can edit it as desired
My goal is to upload a large file to dropbox and because the waiting time can be too long I want to split the process and upload the file through a queue.
I'm doing the following:
I upload a file (that can be large)
I save it on local storage
I save data about the file in database.
In a queue I want to get the file and move it to a dropbox disk.
The problem is that when I do the last step I get the following error
ErrorException
fopen(files/7u7v6LYq72vmXLqeWPsc6b0khiy9pEbFicVJuK2W.pdf): failed to open stream: No such file or directory
I tried different approaches but I can't find a solution.
My code
Controller method:
public function uploadToDropbox(Request $request){
$data = $request->validate([
'file' => 'required|mimes:jpeg,jpg,png,doc,docx,pdf,txt,mp3,mp4,avi|max:600000',
'first_name' => 'required',
'last_name' => 'required',
]);
/** #var \Symfony\Component\HttpFoundation\File\File $uploadedFile */
$uploadedFile = $data['file'];
$path = Storage::disk('local')->putFileAs( 'file', $uploadedFile, $uploadedFile->getClientOriginalName());
$file = new File();
$file->first_name = $data['first_name'];
$file->last_name = $data['last_name'];
$file->file = $path;
$file->original_name = $uploadedFile->getClientOriginalName();
$file->size = $uploadedFile->getSize();
$file->real_path = $uploadedFile->getRealPath();
$file->save();
$result = ProcessFile::dispatch($file);
if($result){
return Redirect::back()->withErrors(['msg'=>'Successfully file uploaded']);
} else {
return Redirect::back()->withErrors(['msg'=>'File failed to upload']);
}
}
Queue job:
public function handle()
{
if (Storage::disk('local')->exists($this->file->file)) {
$name = strtolower($this->file->first_name) . '_' . strtolower($this->file->last_name);
$rez = Storage::disk('dropbox')->putFileAs(
'challenge-files/' . $name . '/',
$this->file->file,
$this->file->original_name
);
Log::info('message: ' . $rez);
} else {
Log::alert('falseeeee');
}
}
FilesystemAdapter puthFileAs method:
public function putFileAs($path, $file, $name, $options = [])
{
$stream = fopen(is_string($file) ? $file : $file->getRealPath(), 'r');
// Next, we will format the path of the file and store the file using a stream since
// they provide better performance than alternatives. Once we write the file this
// stream will get closed automatically by us so the developer doesn't have to.
$result = $this->put(
$path = trim($path.'/'.$name, '/'), $stream, $options
);
if (is_resource($stream)) {
fclose($stream);
}
return $result ? $path : false;
}
filesystems.php local disk configs
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'permissions' => [
'file' => [
'public' => 0664,
'private' => 0600,
],
'dir' => [
'public' => 0775,
'private' => 0700,
],
],
],
Probably, you haven't modify the permissions mappings in your filesystems configuration file.
Look for the
dir
array and check if the
public
number is
0775
if it is not, change it to that number
Look for
file
change 'public' => 0664
I'm building an Restful API using Laravel 5 and MongoDB.
I'm saving avatar image for users.
It's working fine but I'm trying to create a Folder for every User. For example: "app/players/images/USERID"
I've tried to do something like this in different ways but I always get Driver [] is not supported.
\Storage::disk('players'.$user->id)->put($image_name, \File::get($image));
UploadImage:
public function uploadImage(Request $request)
{
$token = $request->header('Authorization');
$jwtAuth = new \JwtAuth();
$user = $jwtAuth->checkToken($token, true);
$image = $request->file('file0');
$validate = \Validator::make($request->all(), [
'file0' => 'required|image|mimes:jpg,jpeg,png'
]);
if ( !$image || $validate->fails() )
{
$data = array(
'code' => 400,
'status' => 'error',
'message' => 'Image uploading error-'
);
}
else
{
$image_name = time().$image->getClientOriginalName();
\Storage::disk('players')->put($image_name, \File::get($image));
$user_update = User::where('_id', $user->id)->update(['imagen' => $image_name]);
$data = array(
'code' => 200,
'status' => 'success',
'user' => $user->id,
'imagen' => $image_name
);
}
return response()->json($data, $data['code']);
}
filesystems.php:
'players' => [
'driver' => 'local',
'root' => storage_path('app/players/images/'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
I expect the user avatar image saves on User ID folder.
The disk call, tells Laravel which filesystem to use, let's assume you have an user with Id one, with your code it will access the filesystem playeers1.
What usually is done is to put these files in folder structures for the different users, so instead you could do. This will put your image file, in the folder 1.
\Storage::disk('players')->put($user->id . '/' . $image_name, \File::get($image));
I had a similar problem, check if the lines can change what you want to achieve.
\Storage::disk('players')->put("{$user->id}/{$image_name}", \File::get($image));
I relied on the laravel guide: File Storage - File Uploads
I hope it helps you. A cordial greeting.
I have a photo upload form which goes to this code
$this->validate($request, [
'image' => 'required|image|max:3000|mimes:jpeg,jpg,png',
]);
$user = Auth::user();
$usersname = $user->username;
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$path = Storage::disk('uploads');
$filename = $usersname . '.' . $ext;
if (Storage::disk('uploads')->has($filename)) {
Storage::delete($filename);
}
Storage::disk('uploads')->put($filename, File::get($file));
$resizedImg = Image::make($path . DIRECTORY_SEPARATOR . $filename)->resize(200,200)->save($path . DIRECTORY_SEPARATOR . $filename);
return redirect()->route('profile.index',
['username' => Auth::user()->username]);
}
When I make this code execute it gives me this error
ErrorException in ProfileController.php line 71:
Object of class Illuminate\Filesystem\FilesystemAdapter could not be converted to string
line 71 is the line beginning with $resizedImg but the photo does save to the correct directory just not resized.
I defined uploads in the filesystems.php file as following
'disks' => [
'uploads' => [
'driver' => 'local',
'root' => public_path('/uploads'),
],
$path contents driver in it, but you're trying to use it as string, that's the problem. Try to use something like:
$path = '/uploads';
I am having some troubles with laravels filesystem uploading.
When I try to execute this code
Storage::disk('public')->put(
$img->getClientOriginalName(),
file_get_contents($img->getRealPath())
);
nothing happens locally in the public folder, I even checked if the file exists and it returns true
dd(Storage::disk('public')->exists($img->getClientOriginalName()));
For now I am using the $img->move method and it works as I want to.
Disk is also configured in filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
I am confused with this because a couple of weeks ago it worked as it should on another project.
I have now fixed this problem with the help of Claudio by using 'root' => public_path('').
This should work:
if ($request->hasFile('myFile'))
{
$fileExtension = strtolower($request->file('myFile')->getClientOriginalExtension());
$newFilename = str_random(20) . '.' . $fileExtension;
$storagePath = storage_path() . '/app/uploads/';
$request->file('myFile')->move($storagePath, $newFilename);
}