Search code examples
dropbox-apiphp-curl

Upload a file into dropbox folder


I have tried this to upload a file from a folder in my desktop to a folder in dropbox account.

but each time i have uploaded an empty file through this code.

How it is possible?

Below s my code:

     $ch = curl_init();
     $TOKEN = "asasasa";//token here
     $url = 'https://content.dropboxapi.com/2/files/upload';
     curl_setopt($ch,CURLOPT_URL,$url);
     curl_setopt($ch,CURLOPT_POST, 1);             
     curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
     $headers = array();
     $headers[] = 'Accept: application/json';
     $headers[] = 'Content-Type: multipart/form-data';
     $headers[] = 'Dropbox-API-Arg:{"path":"/home/new/ofd","mode":{".tag":"add"},"autorename":false,"mute":false}';
     $headers[] = "Authorization: Bearer ".$TOKEN;
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);     
     $response = curl_exec($ch);  
     $droplist  = json_decode($response,true);

Solution

  • You don't seem to be adding the file content to the upload call anywhere, so an empty file is expected from your code.

    You can find an example of using /2/files/upload with curl in PHP below. That uses CURLOPT_INFILE to add the file content itself.



    <?php
    
    $path = 'test_php_upload.txt';
    $fp = fopen($path, 'rb');
    $size = filesize($path);
    
    $cheaders = array('Authorization: Bearer <ACCESS_TOKEN>',
                      'Content-Type: application/octet-stream',
                      'Dropbox-API-Arg: {"path":"/test/'.$path.'", "mode":"add"}');
    
    $ch = curl_init('https://content.dropboxapi.com/2/files/upload');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $cheaders);
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_INFILE, $fp);
    curl_setopt($ch, CURLOPT_INFILESIZE, $size);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    
    echo $response;
    curl_close($ch);
    fclose($fp);
    
    ?>
    

    <ACCESS_TOKEN> should be replaced with the OAuth 2 access token.