簡體   English   中英

在瀏覽器中將PUT上傳到S3時會忽略內容類型嗎?

[英]Ignoring content-type when doing PUT upload to S3 in browser?

在django項目上(幾乎)成功地從瀏覽器設置了s3上傳,我遇到了我似乎無法弄清的最后障礙。 創建簽名以將內容上傳到s3時,似乎沒有任何方法可以忽略設置內容類型。

刪除content-type會有所幫助的原因是,在safari和chrome中,某些文件的擴展名都比較受歡迎(即使.zip也無法使用),這會給我一個“我們計算出的請求簽名與您提供的簽名不匹配“請檢查您的密鑰和簽名方法”,原因是瀏覽器無法識別我所相信的mime類型(至少在我打印出來且出現錯誤時,它為空白)。

這是我遵循的指南: https : //devcenter.heroku.com/articles/s3-upload-python ,除了無法確定mime類型時,它運行良好。 這也是我的稍作修改的代碼的副本:

    import base64
    from hashlib import sha1
    import hmac
    AWS_ACCESS_KEY = 'X'
    AWS_SECRET_KEY = 'XX'
    S3_BUCKET = 'XX/X/X'

    object_name =  urllib.quote_plus(request.GET['s3_object_name'])
    print "object_name: ", object_name.lower()
    mime_type = request.GET['s3_object_type']
    #on some files this is blank and thats the ones that give me 403 errors from s3
    print "mime Type: ", mime_type


    expires = int(time.time()+15)
    amz_headers = "x-amz-acl:public-read"
    # Generate the PUT request that JavaScript will use:
    put_request = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)
    # Generate the signature with which the request can be signed:
    signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, put_request, sha1).digest())
    # Remove surrounding whitespace and quote special characters:
    signature = urllib.quote_plus(signature.strip())

    # Build the URL of the file in anticipation of its imminent upload:
    url = 'https://%s.s3.amazonaws.com/media/attachments/%s' % ('S3_BUCKET', object_name)

    content = json.dumps({
        'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
        'url': url
    })
    print content

    # Return the signed request and the anticipated URL back to the browser in JSON format:
    return HttpResponse(content, mimetype='text/plain; charset=x-user-defined')

基本上,這個問題可以歸因於以下事實:該指南提供的s3_upload.js中讀取file.type結果不正確,因此我修改了這部分代碼

    object_name =  urllib.quote_plus(request.GET['s3_object_name'])
    print "object_name: ", object_name.lower()
    mime_type = request.GET['s3_object_type']
    #on some files this is blank and thats the ones that give me 403 errors from s3
    print "mime Type: ", mime_type

    mime_type = request.GET['s3_object_type']
    print "mime Type: ", mime_type
    mtype,encoding = mimetypes.guess_type(object_name)
    print "guessed mime type", mtype
    mime_type = mtype

然后將內容更改為

content = json.dumps({
        'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
        'url': url,
        'mime_type' : mime_type
    })

並將其傳遞回javascript腳本。 從那里,我剛剛修改了腳本,以在執行放置操作時將mime_type用作內容類型標頭,而不是它在做什么(使用file.type)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM