1

我正在尝试使用 boto 库创建一个超级简单的文件上传脚本,而不是其他任何库。根据我的尝试,感觉它应该可以工作,但事实并非如此。

我现在得到的错误是:

S3ResponseError: 400 Bad Request

这是我认为的代码:

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)

        file = request.FILES['file']
        filename = file.name

        conn = boto.connect_s3()
        bucket = conn.create_bucket('some-bucket-name')
        from boto.s3.key import Key
        k = Key(bucket)

        k.key = filename
        k.send_file(file)
        k.content_type = mimetypes.guess_type(filename)[0] 
        k.set_contents_from_stream(file.chunks())
        k.set_acl('public-read')

        return HttpResponseRedirect('/')
    else:
        form = UploadFileForm()

    return render_to_response('home/upload.html', 
            {'form':form}, 
            context_instance=RequestContext(request))

如果我修改它以在本地保存它可以工作,所以上传到 s3 被破坏了。我已经测试过set_contents_from_string,这适用于字符串数据。但是,任何处理文件或流的东西都会出现上述错误。我是在某处错过了一个设置,还是我在做什么完全错了?

4

2 回答 2

2

我在尝试将文件传输到 S3 时遇到了这个确切的问题。最终,我发现我必须sizeKey调用.send_file

k = Key(bucket)
k.key = 'some-key'
k.size = 12345
k.send_file(file)

可以在文件上使用 seek 和 tell 找到大小。以下将在保留当前文件位置的同时找到大小。在您的情况下,您可以省去记住当前位置,只需在获取文件大小后回零。

position = file.tell()
file.seek(0, os.SEEK_END)
size = file.tell()
file.seek(position)
于 2013-05-07T02:35:08.587 回答
0

I'd be inclined to test your s3 connection and bucket creation step in the shell.

python manage.py shell

I'm curious as to whether or not it's those steps that are tripping you up. For instance if the bucket name you specify isn't globally unique you will receive an error (unsure if it would result in the error code you've received but that is the first place I'd check).

If that is the issue you might consider setting a bucket in the AWS Management Console, then connect to it from your view, and upload files using appropriate 'folder-like' keys based on the needs of your project (see: Amazon S3 boto - how to create a folder?).

于 2011-12-20T19:51:50.753 回答