Dropbox Core API for file uploads

2019-09-11 10:54发布

问题:

I run a service that is visited by its users to generate PDF documents that are then delivered to them by email. I am in the process of exploring an alternative delivery route - popping the prepared document directly in a Dropbox folder that they designate.

After a spot of research I discovered the Dropbox API and then played with their "explorer" here. Examining the cURL they generate to perform a file upload I found that it could quite easily be done with a spot of PHP. After creating a new app I then wrote out a little PHP script

$headers = array('Authorization: Bearer ul...',
                  'Content-Type: application/octet-stream',
                  'Dropbox-API-Arg: {"path":"/test.txt","mode":"add"}');
$data = 'Betty bought a bit of butter';

$ch = curl_init('https://content.dropboxapi.com/2-beta-2/files/upload/');
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

On running this script everything worked just perfectly - the file in question turned up in my Dropbox in a fraction of a second.

All very nice. However, I am into my first few minutes with the Dropbox API and there is much that I do not understand here

  • Is the code I wrote above by blindly mimicking their explorer sample code the right way to do file uploads?
  • In my case it is the users of my service who will have to provide me with a valid App token I can use above in the Authorization:Bearer... bit. I assume that this token constrains me to only working within the confines of their app folder? They would, naturally, be unwilling to hand over a token that lets me do what I will with their Dropbox. *Needless to say - this would be conditional on their configuring their "App" permission type to App Folder.

I'd much appreciate any feedback I can get on my approach - particularly the flaws in it - from those who know the Dropbox API better than I.

回答1:

The Dropbox API Explorer uses the new Dropbox API v2, which just came out of beta. You can find the official documentation, including a curl example, here:

https://www.dropbox.com/developers/documentation/http#documentation-files-upload

As long as you're using it as documented there, (e.g., you should use /2/ now instead of /2-beta-2/), it should be fine.

Regarding permissions, there are a few to pick from (though API v2 currently only supports app folder and full Dropbox), and the permission is chosen by the developer when the app is registered:

https://www.dropbox.com/developers/reference/devguide#app-permissions

The access token your app gets for a user's Dropbox account once they link to the app is constrained to the app's permission.

In your case, it sounds like the app folder permission would be sufficient.