2014-09-02 69 views
6

我們正試圖使用​​jQuery ajax &將文件上傳到預先註冊的url。我們在服務器上生成預先註冊的url。目前我們正在嘗試使用FormData來上傳文件。使用JQuery將文件上傳到S3,使用預先登記的URL

  var uploadData = new FormData(), 
      files = $(this.input).prop('files'), 
      file = files[0]; 

      uploadData.append('file', file); 

      $.ajax({ 
      url: '{presigned url string}', 
      type: 'PUT', 
      data: uploadData, 
      cache: false, 
      processData: false, 
      contentType: false, 
      success: function(response) { 
       console.log('S3 upload success!'); 
      }, 
      error: function(response) { 
       console.log('Error with S3 upload: ' + response.statusText); 
      } 
      }); 

這將返回從AWS一個SignatureDoesNotMatch錯誤:

<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 0a 6d 75 6c 74 69 70 61 72 74 2f 66 6f 72 6d 2d 64 61 74 61 3b 20 62 6f 75 6e 64 61 72 79 3d 2d 2d 2d 2d 57 65 62 4b 69 74 46 6f 72 6d 42 6f 75 6e 64 61 72 79 67 57 6f 4a 73 42 56 79 41 4c 57 71 51 6b 73 69 0a 31 34 30 39 37 37 37 32 39 33 0a 2f 64 69 2d 6b 79 72 73 74 65 6e 2d 64 65 61 6c 73 2f 76 4e 79 4b 4e 55 4c 37 51 68 4f 30 45 4b 38 52 58 44 70 32 59 77 25 32 46 63 35 37 65 64 37 62 39 2d 64 63 61 62 2d 34 63 30 62 2d 62 36 63 30 2d 36 31 66 30 36 62 32 30 37 34 66 31 2d 74 65 73 74 2e 74 78 74</StringToSignBytes> 
<RequestId>ED7C581570F547DB</RequestId><HostId>ZT6LsFYCbo1L0gYNcUwtdCWF6SNnyuUyKiL60ntJEZugx3cnDN/yH5KBjgEiBv5c</HostId><SignatureProvided>N2d7oNMVHvI6yxAXujNy8O5cF24=</SignatureProvided> 
<StringToSign>PUT 

multipart/form-data; boundary=----WebKitFormBoundarygWoJsBVyALWqQksi 
1409777293 
/test-bucket/vNyKNUL7QhO0EK8RXDp2Yw%2Fc57ed7b9-dcab-4c0b-b6c0-61f06b2074f1-test.txt</StringToSign><AWSAccessKeyId>FAKEACCESSKEY</AWSAccessKeyId></Error> 

我知道presigned鏈接的作品,因爲我可以通過捲曲正確上傳的文件:

curl -v --upload-file {filename} {presigned url} 

回答

7

我們發現問題我們自己。下面是我們使用生成預簽名URL代碼:我們不得不設置在presignedUrlRequest內容類型以及添加
headers: {'Content-Type': 'multipart/form-data'}我們的AJAX調用

val dt: DateTime = new DateTime() 
val expiration = DateTime.now.plusMillis(timeout.toInt) 
val presignedUrlRequest: GeneratePresignedUrlRequest = 
    new GeneratePresignedUrlRequest(awsBucket, key, HttpMethod.PUT) 
presignedUrlRequest.setExpiration(expiration.toDate()) 
// WE ADDED THIS LINE 
presignedUrlRequest.setContentType("multipart/form-data") 

s3client.generatePresignedUrl(presignedUrlRequest).toString() 

由於我們沒有在presignedUrlRequest中設置內容類型,curl沒有設置內容類型,所以我們首先使用CURL生成url的方式。

+0

我遇到同樣的問題,但設置內容類型沒有幫助。會喜歡一些幫助! – kungfoo 2015-03-06 13:26:22

+0

該解決方案對我很好,但上傳到S3的文件附帶了FormData值。你知道如何防止這種情況嗎? – schoonie23 2015-10-01 22:03:58

相關問題