开发者

Using Urllib instead of action in post form

I need to allow users to upload content directly to Amazon S3. This form works:

<form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">{% csrf_token %}
    <input type="hidden" name="key" value="videos/test.jpg">
    <input type="hidden" name="AWSAccessKeyId" value="<access_key>"> 
    <input type="hidden" name="acl" value="public-read">
    <input type="hidden" name="policy" value="{{policy}}">
    <input type="hidden" name="signature" value="{{signature}}">
    <input type="hidden" name="Content-Type" value="image/jpeg">
    <input type="submit" value="Upload" name="upload">
</form>

And in the function, I define policy and signature. However, I need to pass two variables to the form -- Content-Type and Key, which will only be known when the user presses the upload button. Thus, I need to pass these two variables to the template after the POST request but before the re-direction to Amazon.

It was suggested that I use urllib to do this. I have tried doing so the following way, but I keep getting an inscrutable HTTPError. This is what I currently have:

开发者_开发知识库
if request.method == 'POST':
    # define the variables
    urllib2.urlopen("https://me.amazonaws.com/", 
                           urllib.urlencode([('key','videos/test3.jpg'),  
                           ('AWSAccessKeyId','<access_key'), 
                           ('acl','public-read'), 
                           ('policy',policy),
                           ('signature',signature),
                           ('Content-Type',content_type),
                           ('file',file)]))

I have also tried hardcoding all the values instead of using variables but still get the same error. What am I doing incorrectly and what do I need to change to be able to redirect the form to Amazon, so the content can be uploaded directly to Amazon?


I recommend watching the form do its work with Firebug, enabled and set to the Net tab.

After completing the POST, click its [+] icon to expand, study the Headers, POST, Response tabs to see what you are missing and/or doing wrong.

Next separate this script from Django and put into a standalone file. Add one thing at a time to it and retest until it works. The lines below should increase visibility into your script.

import httplib
httplib.HTTPConnection.debuglevel = 1

I tried poking around with urllib myself, but as I don't have an account on AWS I didn't get farther than getting a 400 Bad Request response. Seems like a good sign, probably I just need valid host and key params etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜