简体   繁体   中英

Dropbox API - trying to upload a file

I've just rebuilt my Raspberry Pi and hence installed the latest version of the Dropbox API and now my program doesn't work. I think this is due to point 1 in these breaking changes: https://github.com/dropbox/dropbox-sdk-python/releases/tag/v7.1.0 . I'm sure this question from SO ( Dropbox API v2 - trying to upload file with files_upload() - throws TypeError ) solves my problem... but as a newbie, I can't figure out how to actually implement it - and anyway, I'm already using f.read() ... can anyone help?

This is my code:

def DropboxUpload(file):
    sourcefile = "/home/pi/Documents/iot_pm2/dropbox_transfer/" + filename
    targetfile = "/" + filename
    dbx = dropbox.Dropbox(cfg.dropboxtoken)
    f = open(sourcefile, "r")
    filecontents = f.read()
    try:
        dbx.files_upload(filecontents, targetfile, mode=dropbox.files.WriteMode.overwrite)
    except dropbox.exceptions.ApiError as err:
        print(err)
    f.close()

And this is the error:

Traceback (most recent call last):
  File "/home/pi/Documents/iot_pm2/dropbox_uploader.py", line 20, in <module>
    DropboxUpload(filename)
  File "/home/pi/Documents/iot_pm2/dropbox_uploader.py", line 12, in DropboxUpload
    dbx.files_upload(filecontents, targetfile, mode=dropbox.files.WriteMode.overwrite)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/base.py", line 2125, in files_upload
    f,
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 272, in request
    timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 363, in request_json_string_with_retry
    timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/dropbox/dropbox.py", line 407, in request_json_string
    type(request_binary))
TypeError: expected request_binary as binary type, got <class 'str'>

Thanks in advance.

You need to supply bytes , but you're supplying str .

You can get bytes by changing the file mode to binary. Ie, instead of:

f = open(sourcefile, "r")

do:

f = open(sourcefile, "rb")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM