How to get url from dropbox using flysystem? - laravel

Hello i has upload my file using laravel5, https://github.com/GrahamCampbell/Laravel-Dropbox integrate to dropbox and has succeed, and then i want to get the url for my imgsrc="" on the frontend, How i can get thats url?
dd(Flysystem::get('avatars/kenshin.jpg'));
Where is the url for imgsrc?

Assuming you already created a service provider for custom filesystem.
If you don't know how to do that the doc is Here
Route::get('/dropbox',function()
{
$filename = '/text1.txt';
$adapter = \Storage::disk('dropbox')->getAdapter();
$client = $adapter->getClient();
$link = $client->createTemporaryDirectLink($filename);
return <<<EOT
Link
EOT;
});
PLEASE NOTE THAT you have to prefix a "\" slash on the filename or else it will thrown an exception.

I save a shared link while saving a new resource. Like so
$path = Storage::disk('dropbox')->putFile('/images', storage_path('images/' . $imageName));
$adapter = \Storage::disk('dropbox')->getDriver()->getAdapter();
$client = $adapter->getClient();
$link = $client->createSharedLinkWithSettings($path);
$newsdigest = NewsDigest::create($request->all('title','type','source', 'article') + [
'reading_attachment' => $link['url']
]);

Create another route for a method in your controller and pass the file name that you want to access from dropbox with the route.
Use getFile() method in your controller and pass the filename to the variable.
public function getFile($file_name)
{
$client = new Client('dropbox.token','dropbox.appName');
$this->filesystem = new Filesystem(new Dropbox($client, '/path'));
try{
$file = $this->filesystem->read($file_name);
}catch (\Dropbox\Exception $e){
return Response::json("{'message' => 'File not found'}", 404);
}
$response = Response::make($file, 200);
return $response;
}

The best way I found to upload your file in Dropbox and even get share files link in your PHP or Laravel or any PHP framework is by using this package
composer require kunalvarma05/dropbox-php-sdk
This is how to use it, an example I made using Laravel:

Related

Return images from storage folder

I have some images in the storage folder. I want to get them in response and show to my users.
What I try:
I use the following code but it returns NULL:
// All images are in the storage/app/users/{id}/document folder
$path = storage_path( 'app/users/'.$id . '/document');
if (!File::exists($path)) {
abort(404);
}
$file = File::files($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
Output: Null
Where is my mistake?
Is there a better solution?
By the laravel documentation
you can resolve this.
return Storage::files('users/'.$id .'/document')
the default path of store file in laravel is storage/app/public and by default you should not set this path and your path is after this and laravel by default start from this path
and remember to add use Illuminate\Support\Facades\Storage;
in top of your class

Incorrect URL from AWS S3 with Laravel File Upload

I'm uploading an image to S3 with Laravel as follows:
$image = $request->image;
if (!empty($image)) {
$imageFileName = $user_id.'_'.rand(11111111, 99999999) . '.' . $image->getClientOriginalExtension(); // Rename Image
try
{
//Send to S3
$s3 = Storage::disk('s3');
$filePath = '/profile/' . $imageFileName;
$s3->put($filePath, file_get_contents($image), 'public');
$image = Storage::cloud()->url($imageFileName);
}
catch(\Exception $exx)
{
//Send to Logs Etc
}
The image uploads successfully but I need to store the URL in my database. This is being called here:
$image = Storage::cloud()->url($imageFileName);
The issue is the URL being returned, it looks like this:
http://test-env.XXX.us-west-2.elasticbeanstalk.com/profile/https://elasticbeanstalk-us-west-2-123XXX456XXX.s3.us-west-2.amazonaws.com/6_52644340.jpg
Hence:
http://mentr-test-env.2w8sh3esch.us-west-2.elasticbeanstalk.com/profile/
is somewhat-correct. But the next piece is missing the 'profile' sub-folder, and obviously starts at HTTPS again:
https://elasticbeanstalk-us-west-2-123XXX456XXX.s3.us-west-2.amazonaws.com/6_52644340.jpg
It would appear I'm getting two halves of the link in a single string. I don't edit the $image variable anywhere else.
The correct link is:
https://elasticbeanstalk-us-west-2-123XXX456XXX.s3.us-west-2.amazonaws.com/profile/6_52644340.jpg
I have confirmed the files are uploading correctly and publicly available.
I have tried calling:
$image = Storage::cloud()->url($filePath);
And this returns:
http://test-env.XXXX.us-west-2.elasticbeanstalk.com/profile/https://elasticbeanstalk-us-west-2-XXX123XXX.s3.us-west-2.amazonaws.com//profile/6_31595766.jpg
Update
I just noticed the first part of the returned URL is the BeanStalk instance URL with the /profile/ added. This is even stranger as I don't wish to use Beanstalk, I only want to use S3.
If you want to store the entire url you can get it from the return variable passed back from the put() function.
$s3_url = $s3->put($filePath, file_get_contents($image), 'public');
Sometimes I like to just store the path though and save just that piece to the database then I can pass the path to Storage::url($filePath); and it still works.
$image = $request->image;
if (!empty($image)) {
$imageFileName = $user_id.'_'.rand(11111111, 99999999) . '.' . $image->getClientOriginalExtension(); // Rename Image
try
{
//Send to S3
$s3 = Storage::disk('s3');
$filePath = '/profile/' . $imageFileName;
$s3->put($filePath, file_get_contents($image), 'public');
$image = Storage::cloud()->url('s3-url/s3-bucket'.'/'.$filepath);
}
catch(\Exception $exx)
{
//Send to Logs Etc
}

How can I save image in subfolder using Amazon aws3 | Laravel

I am using aws to store my images and the code in the controller looks like this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public');
The images are being saved in my local storage.
Now though, I want to be able to create a subfolder to keep the images organized.
For my case, it is registering a business. Therefore I want the images to be stored in a subfolder containing the appropriate business id. I tried this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id.
More about the controller is as follows:
$input = $request->all();
$files = isset($input['file']) ? $input['file'] : array ();
$business_names = json_decode($input['business_names'], true);
$business_details = json_decode($input['business_details']);
$share_amount = json_decode($input['share_amount'], true);
$entity = json_decode($input['entity'], true);
$directors = json_decode($input['directors'], true);
$shareholders = json_decode($input['shareholders'], true);
$appointments = json_decode($input['appointments'], true);
$input['user_id'] = Auth::user()->id;
Log::info(Auth::user());
Log::info($request->user());
/* Create Business Record */
$business = new Business;
$business->business_names = json_encode($business_names);
$business->share_amount = $share_amount ?: 0;
$business->entity = $entity ?: '';
$business->business_physical_address = json_encode($business_details->physical_address);
$business->has_business_postal_address = $business_details->has_postal_address;
$business->business_postal_address = json_encode($business_details->postal_address);
$business->user_id = $input['user_id'];
$business->save();
/* Create a new folder in storage/app/files named after the business ID */
Storage::makeDirectory('files/' . $business->id);
/* Upload Files */
// TODO: file storing?
foreach($files as $file) {
if ($file) {
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id);
// $file->storeAs('files/' . $business->id, $file->getClientOriginalName());
}
}
When I try to save a business now, I see the following error:
C:\xampp\htdocs\startingabandbaby\vendor\league\flysystem\src\Adapter\Local.php(356):
Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8,
'Undefined index...', 'C:\xampp\htdocs...', 356, Array)
Since I was able to store images before, I am assuming that it is something to do with concatenating the business id.
How can I create a subfolder with the business id everytime I create a new business and add all the files in that same folder?
As per our discussion, you can use below 2 solutions:
1) put():
$path = Storage::disk('s3')->put(
'/files/'. $business->id, //path you want to upload image to S3
file_get_contents($request->file('file')), //fileContent
'public' //visibility
2) putFileAs(): To achieve the same thing withputFileAs(), I needed to write it as below. 1st parameter expects the directory name, I left it blank as I'm mimicking the directory name in s3 through the filename.
$path = Storage::disk('s3')->putFileAs(
'', // 1st parameter expects directory name, I left it blank as I'm mimicking the directory name through the filename
'/files/'. $business->id,
$request->file('file'), //3rd parameter file resource
['visibility' => 'public'] //options
);
Hope this will helps you!
After some research I ended up with the following:
$directory = 'public/' . $business->id;
Storage::disk()->makeDirectory($directory);
foreach($files as $file) {
if ($file) {
Storage::disk()->put($directory . '/' .$file->getClientOriginalName(), fopen($file, 'r+'));
}
}

Laravel Error Server Error after uploading File - Permission Server html_public

I can upload correctly my files in my Localhost inside /public. But in my server i got Error Server. Maybe i need to change somes permissions or set storage path. I tried all my best but i dn't know much about permissions. Can some one help me to resolve that please ?
This is my controller code :
public function addPerson(Request $request)
{
$person = new Person;
$exploded = explode(',', $request->image);
$decoded = base64_decode($exploded[1]);
if (str_contains($exploded[0], 'jpeg')) {
$extension="jpg";
} else {
$extension="png";
}
$fileName = str_random().'.'.$extension;
$path = public_path().'/'.$fileName;
file_put_contents($path, $decoded);
$person->photo = $fileName;
$person->save();
return back()->with('success', 'New Position added successfully.');
}
Since i uploaded my Project in Cpanel, i didn't change something. Thank you.
update :
I activate app_debug , and got this problem instead

Session not remember, and why the session created each time I load the page?

I start to work with my project using laravel 5. I realized that it work fine in my local directory with session after I login to my site, But I just know that I got problem when I hosted my project to server. After I login each time, the session could not remember and recreated each time I loan the page. That cause the problem to me.
Laravel Login
public function postLogin(){
$hit = 0;
if(Request::ajax()){
$pw = Request::input('pw');
if(!empty($pw)){
$admin_pass = AdminPassword::first(['admin_pass']);
$ip_address = Request::ip();
if(!empty($admin_pass) && trim($admin_pass->admin_pass) == trim($pw)){
if(Auth::attempt(['username' => Request::input('username'), 'password' => Request::input('password'),'status'=>1])){
try{
$user = Auth::user();
$user->last_login = date('Y-m-d H:i:s');
$user->login_ip = $ip_address;
$user->save();
$permissions = Auth::user()->permission;
if(!empty($permissions) && count($permissions) >0){
session(['ROLE_PERMISSION'=>$permissions]);
}
$failed = FailedLogin::whereRaw('ip_address = INET_ATON(\''.$ip_address.'\')')->first();
if(!empty($failed)){
$failed->delete();
}
}catch (\Exception $ex){}
$url = Request::session()->pull('url.intended', '/');
return ['url'=>$url,'msg'=>'Successfully.','status'=>true,'hit'=>$hit];
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}
}else{
return redirect()->route('login');
}
return ['url'=>'','msg'=>'Try again.','status'=>false,'hit'=>$hit];
}
Please help me out. This is the final step of my project.
Thank you in advanced.
It's possible you have SESSION_DRIVER in your .env set to file - depending on your hosting environment, this could mean that your session isn't persisting due to each request being served from a different file server (common in cloud environments).
Try changing your SESSION_DRIVER to database.
Did you put the
session_start();
in all your pages?
If not it might be your problem, I d suggest you to add this in your index directly

Resources