Search code examples
pythondropbox-api

Dropbox API v2 - uploading files


I'm trying to loop through a folder structure in python and upload each file it finds to a specified folder. The problem is that it's uploading a file with the correct name, however there is no content and the file size is only 10 bytes.

import dropbox, sys, os
try:
  dbx = dropbox.Dropbox('some_access_token')
  user = dbx.users_get_current_account()
except:
  print ("Negative, Ghostrider")
  sys.exit()

rootdir = os.getcwd()

print ("Attempting to upload...")
for subdir, dirs, files in os.walk(rootdir):
      for file in files:
        try:  
          dbx.files_upload("afolder",'/bfolder/' + file, mute=True)
          print("Uploaded " + file)
        except:
          print("Failed to upload " + file)
print("Finished upload.")

Solution

  • Your call to dbx.files_upload("afolder",'/bfolder/' + file, mute=True) says: "Send the text afolder and write it as a file named '/bfolder/' + file".

    From doc:

    files_upload(f, path, mode=WriteMode('add', None), autorename=False, client_modified=None, mute=False)
    Create a new file with the contents provided in the request.

    Parameters:

    • f – A string or file-like obj of data.
    • path (str) – Path in the user’s Dropbox to save the file.
      ....

    Meaning that f must be the content of the file (and not the filename string).

    Here is a working example:

    import dropbox, sys, os
    
    dbx = dropbox.Dropbox('token')
    rootdir = '/tmp/test' 
    
    print ("Attempting to upload...")
    # walk return first the current folder that it walk, then tuples of dirs and files not "subdir, dirs, files"
    for dir, dirs, files in os.walk(rootdir):
        for file in files:
            try:
                file_path = os.path.join(dir, file)
                dest_path = os.path.join('/test', file)
                print 'Uploading %s to %s' % (file_path, dest_path)
                with open(file_path) as f:
                    dbx.files_upload(f, dest_path, mute=True)
            except Exception as err:
                print("Failed to upload %s\n%s" % (file, err))
    
    print("Finished upload.")
    

    EDIT: For Python3 the following should be used:

    dbx.files_upload(f.read(), dest_path, mute=True)