Dropbox with Laravel: best way to set up, upload, download, choose

Dropbox with Laravel: best way to set up, upload, download, choose

dropbox

In this article, you’ll learn to integrate the Dropbox API v2 into a Laravel project. The content is basically broken down like this:

  1. Introduction
  2. Set Up Dropbox App and Laravel project
  3. Upload Files
  4. List Files And Folders
  5. Download Files
  6. Let User Choose Files

1. Introduction

Dropbox is a very famous file hosting service that offers cloud storage, file synchronization, and personal cloud. Dropbox was founded in 2007, and nowadays is available in more than 22 languages and has more than 700 millions of users.

We are going to learn how to integrate our Laravel project with Dropbox API (v2) in an easy way.

Curiously, most of the articles on the internet are teaching only to use Dropbox as a backup for your Laravel project, so I want to dive deeper into some Dropbox resources, as Download, Upload, List files and folders, let the users choose file or folder.

2. Set Up Dropbox App and Laravel project

2.1. Setting up the Dropbox App

First of all, we’re going to need create a Dropbox account.

With that said, you need creating an APP at https://www.dropbox.com/developers/apps

When we are creating an APP, we are asked whether we want a Folder Access or a Full Access App. This option depends on what you need. In my case, I’ve chosen Full Dropbox Access.

Now that we’ve created our Dropbox App, we have your App’s key and secret.

Also, we need to set the redirect URL. This URL will be called when the user allows connecting to the Dropbox App. For example http://localhost/dropbox/connect

2.2. Setting up your Laravel project

I presume you have already created your Laravel project, so we are going to need to install a package to deal with Dropbox API:

composer require dcblogdev/laravel-dropbox

We can publish the config file with

php artisan vendor:publish --provider="Dcblogdev\Dropbox\DropboxServiceProvider" --tag="config"

Publish the migrations to create the tokens table

php artisan vendor:publish --provider="Dcblogdev\Dropbox\DropboxServiceProvider" --tag="migrations"

Run the migration

php artisan migrate

We need to add this to our .env file, replacing the values for ours. Remember that the key and secret are from Dropbox App (image 2):

DROPBOX_CLIENT_ID=Key
DROPBOX_SECRET_ID=Secret
DROPBOX_OAUTH_URL=http://localhost/dropbox/connect
DROPBOX_LANDING_URL=http://localhost/dropbox
DROPBOX_ACCESS_TYPE=offline

2.3. Setting up the routes

Now we need to create routes to manage the Dropbox connection:

Route::group(['middleware' => ['web', 'auth']], function(){
    Route::get('dropbox/connect', function(){
        return Dropbox::connect();
    });

    Route::get('dropbox/disconnect', function(){
        return Dropbox::disconnect('app/dropbox');
    });
});

3. Upload Files

In your controller or service, you can easily upload a file to Dropbox using this method:

Dropbox::files()->upload($dropboxPathToSave, $fileToUpload)

4. List Files And Folders

It is easy to list a directory files and folders.

$folderContent = Dropbox::files()->listContents($dropboxFolderPath);

If the directory has many files we might see two parameters called has_more and cursor. This indicates that the result is paginated. So you are going to need to call another method in a loop to get all the files:

$folderContent = Dropbox::files()->listContents($dropboxFolderPath);

$entries = $folderContent['entries'];

while ($folderContent['has_more']) {
  $folderContent = Dropbox::files()->listContentsContinue($folderContent['cursor']);
  $entries = array_merge($entries, $folderContent['entries']);
}

foreach ($entries as $entry) {
  //if you want to ignore the folders
  if ($entry['.tag'] === 'folder') {
    continue;
  }
  
  //we can use the file data here
  //entry['path_lower'] => full path to the file. You can use this path to download the file
  //entry['name'] => name saved in the Dropbox
  //entry['id'] => Unique ID to indentify the file in the Dropbox
  //entry['size'] => Size of the file
  //...
}

5. Download Files

Dropbox::files()->download($dropboxFilePathToDownload, $localFolderToSaveIt)

6. Let Users Choose File or Folder

Sometimes you might want to add an HTML input to a page to allow the user to choose a file from our Dropbox App. Dropbox makes this easy by using JavaScript code. You need to load the script to your page:

<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="fhjim2t3fns0dad"></script>
//...
<input type="text" class="db-chooser" name="dropbox_file_shared_link">
//...
<script>
	$('.db-chooser').on('click', function(e) {
  		e.preventDefault();
  		
  		Dropbox.choose({
          folderSelect: false, //if we want allow the user select folders, use true
          extensions: ['images'], //if we want allow the user select videos, add 'video',
          success: function(files) {
            $(this).val(files[0].link);
          }
        });
	});

When the user choose a file, in the input we are going to have the shared link to that file. Something like this: https://www.dropbox.com/s/og6zu8ziozf2t/filename.jpg?dl=0

Now, in our controller you need a way to get the Dropbox file path by using this shared URL.

First, you need add our domain to our Dropbox App Chooser list:

And we need add permission to our App access shared metadata, on the Permissions tab:

In the backend you need a new method to get the metadata information by the shared link:

use Dcblogdev\Dropbox\Facades\Dropbox;
//...

	/**
     * @param  string  $link
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getSharingMetadataByLink(string $link): array
    {
        $client = new \GuzzleHttp\Client;

        $response = $client->post('https://api.dropboxapi.com/2/sharing/get_shared_link_metadata', [
            'headers' => [
                'Authorization' => 'Bearer ' . Dropbox::getAccessToken(),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode([
                 'url' => $link
             ])
        ]);

        return json_decode($response->getBody(), true);
    }

Now, we can get the Dropbox file path passing the link sent by the form:

$fileSharedLink = request()->get('dropbox_file_shared_link');
$fileMetadata = $this->getSharingMetadataByLink($fileSharedLink);
//we can use the $fileMetadata['path_lower']

References

Laravel-dropbox package: https://github.com/dcblogdev/laravel-dropbox

Dropbox chooser: https://www.dropbox.com/developers/chooser

Quick information about Dropbox: https://en.wikipedia.org/wiki/Dropbox

Dropbox official website: https://www.dropbox.com/

Considerations

Dropbox uses OAuth2 and its token has a life of 4 hours. I like to use this Laravel package, even being very limited, because when the token gets invalid, it creates another valid token, and it makes it easy to we get this token to use in other endpoints, using this method `Dropbox::getAccessToken()`.

I recommend you read this other article of Vimeo with Laravel: how to integrate in a easy way.

As you read this article, please help me by sharing this post with your friends and letting a comment below.

Share this content:

Robson Sousa

I’m Brazilian, married to Ludmila and Júlia’s father. I have lived in Timon, Teresina, Uberaba and now Goiânia. I had my first job as a Software Developer at 2010. From there to here, I have met so much talented people, learnt a lot from each different experience and collegues, and shared knowledge.

Subscribe
Notify of
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Alejandro Hurtado
1 ano atrás

do you have a tutorial video?

1 ano atrás

[…] I recommend you read this other article of The Right Way To Integrate Dropbox to Laravel. […]