【发布时间】:2016-02-23 18:56:04
【问题描述】:
尝试将文件上传到 S3:
# boto3 s3 client
s3.put_object(Bucket=self.bucket,
Body=open(upload_file, 'rb'),
Key=k.key,
SSECustomerAlgorithm='AES256',
SSECustomerKey=base64.b64encode(data_key),
SSECustomerKeyMD5=base64.b64encode(data_key_md5)
)
并在这一行出错:
TypeError: coercing to Unicode: need string or buffer, file found
我的upload_file 变量是<type 'file'> 和dir:
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
切换到open(upload_file, 'rb').read() 无济于事。我的文件也可能很大(1gb pr 所以),将它们保留为字符串是不合理的。
我知道如果我将upload_file 设置为文件路径,它会起作用,但我的磁盘上没有这个文件,它是通过表单提交的。
更新
这很奇怪,但是当我使用测试文件或字符串(为了测试)时遇到了类似的问题:
TypeError: expected string or buffer
这是对:
# boto3 s3 client
s3.put_object(Bucket=self.bucket,
# put existing filr
Body=open('/tml/existing-file', 'rb'), # adding read() wont help
# ...
)
字符串也一样:
# boto3 s3 client
s3.put_object(Bucket=self.bucket,
# put existing filr
Body='some random string',
# ...
)
【问题讨论】:
-
设置
Body=open(upload_file, 'rb').read()时遇到什么错误? -
@wilbur
*** TypeError: coercing to Unicode: need string or buffer, file found这个文件来自表单,<open file '<fdopen>', mode 'w+b' at ***> -
如果您只是将
upload_file传递给Body而不是尝试打开它呢? -
@wilbur 如果我通过了
upload_file我得到了错误TypeError: expected string or buffer与upload_file.read()相同 -
您能提供完整的回溯吗?
标签: python python-2.7 boto boto3