以下代码在S3中存储上传的文件:
def store_in_s3(filename, filecontent, type, modelname, format, manufacturer, adder_id):
extension = os.path.splitext(filename)[1]
filename = modelname + "-" + manufacturer + "-" + type + "-" + format + "-" + str(adder_id) + extension
pathtofile = "Parts/%s" % (filename)
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
b = conn.create_bucket('mybucket')
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = "/media/Parts/%s" % (filename)
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(filecontent)
k.set_acl("public-read")
return pathtofile
它适用于图像和文本文件,但是当我尝试上传某些文件类型时,我得到了回复并且不确定原因:
<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><StringToSignBytes>50 55 54 0a 66 33 5a 74 6f 74 50 4e 50 4a 62 59 69 6e 67 68 38 38 45 39 45 67 3d 3d 0a 4e 6f 6e 65 0a 57 65 64 2c 20 30 37 20 4e 6f 76 20 32 30 31 32 20 31 36 3a 30 38 3a 35 37 20 47 4d 54 0a 2f 73 6e 61 70 65 64 61 2f 6d 65 64 69 61 2f 43 41 44 50 61 72 74 73 2f 61 64 37 31 31 2d 41 53 44 41 2d 4d 6f 64 65 6c 2d 53 50 49 43 45 2d 31 2e 63 69 72</StringToSignBytes
回溯:
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/spicestore/spices/views.py" in add_model
577. new_model.content=store_in_s3(filename, filecontent, type, modelname, format, manufacturer, adder_id)
File "/Users/nb/Desktop/spicestore/store_in_s3.py" in store_in_s3
24. k.set_contents_from_string(filecontent)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/s3/key.py" in set_contents_from_string
1124. encrypt_key=encrypt_key)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/s3/key.py" in set_contents_from_file
994. chunked_transfer=chunked_transfer, size=size)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/s3/key.py" in send_file
727. query_args=query_args)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/s3/connection.py" in make_request
468. override_num_retries=override_num_retries)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/connection.py" in make_request
910. return self._mexe(http_request, sender, override_num_retries)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/connection.py" in _mexe
810. request.body, request.headers)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/boto/s3/key.py" in sender
684. response.status, response.reason, body)
Exception Type: S3ResponseError at /spices/add
Exception Value: S3ResponseError: 403 Forbidden
答案 0 :(得分:1)
在您的代码中:
k.set_metadata("Content-Type", mime)
mime必须为None,看起来s3不允许文件的Content-Type为None。您可以删除它,该文件将被设置为s3中的默认内容类型。
使用时
mimetypes.guess_type(filename)
文件名应以文件扩展名结尾,例如www.test.com/1.jpg?code=XXXX
mimetype无法猜测类型,将返回None。