Dropbox API v2 - 上传文件

4
我正在尝试使用Python遍历文件夹结构并将找到的每个文件上传到指定的文件夹。问题在于它上传了一个具有正确名称的文件,但没有内容,文件大小仅为10字节。
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.")
2个回答

12

您调用了dbx.files_upload("afolder",'/bfolder/' + file, mute=True)函数,意味着"发送文本afolder并将其命名为'/bfolder/' + file"。

文档看:

files_upload(f, path, mode=WriteMode('add', None), autorename=False, client_modified=None, mute=False)
使用请求中提供的内容创建新文件。

参数:

  • f – 数据的字符串或类似文件的对象
  • path (str) – 要保存文件的用户Dropbox中的路径。
    ....

这意味着f必须是文件的内容(而不是文件名字符串)。

以下是可行的示例:

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.")

编辑:对于Python3,应该使用以下代码:

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


1
@MikeResoli,您具体看了什么让您产生了误解?我们很乐意借此机会改进网站。 - user94559
@smarx,这个页面上有,但现在回头看,我意识到自己看起来很愚蠢:https://www.dropbox.com/developers/documentation/python#tutorialdbx.files_upload("潜在标题:勇士队以微弱优势战胜骑士队的第五场比赛紧张刺激", '/cavs vs warriors/game 5/story.txt') 我假设第一个参数是上传文件的描述标签。 - Mike Resoli
2
我认为展示一个文件实例会比展示一个字符串更清晰。或者使用类似于“要发送的文件内容”的自描述字符串。 - Cyrbil
@smarx 感谢您回复我,很高兴看到Dropbox希望改善客户体验。我同意他的建议,一个描述字符串会更合适。 - Mike Resoli
不想打扰大家,这个关于字符串或文件对象 f 的问题也让我来到了这个帖子,感谢 @Cyrbil 提供的示例。 - sgauri
显示剩余3条评论

1
以下是上传文件到Dropbox Business API的Python代码:

#功能代码

import dropbox

def dropbox_file_upload(access_token,dropbox_file_path,local_file_name):

'''
The function upload file to dropbox.

    Parameters:
        access_token(str): Access token to authinticate dropbox
        dropbox_file_path(str): dropboth file path along with file name
        Eg: '/ab/Input/f_name.xlsx'
        local_file_name(str): local file name with path from where file needs to be uploaded
        Eg: 'f_name.xlsx' # if working directory
Returns:
    Boolean: 
        True on successful upload
        False on unsuccessful upload
'''
try:
    dbx = dropbox.DropboxTeam(access_token)
    # get the team member id for common user
    members = dbx.team_members_list()
    for i in range(0,len(members.members)):
        if members.members[i].profile.name.display_name == logged_in_user:
            member_id = members.members[i].profile.team_member_id
            break
    # connect to dropbox with member id
    dbx = dropbox.DropboxTeam(access_token).as_user(member_id)
    # upload local file to dropbox
    f = open(local_file_name, 'rb')
    dbx.files_upload(f.read(),dropbox_file_path)
    return True
except Exception as e:
    print(e)
    return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接