2013-08-22 27 views
2

我有一個工作的HTML表單POST上傳到亞馬遜S3:HTML POST - >重定向工作,XMLHTTPrequest - >重定向不工作(不能從空任何請求)?

<form action="https://bucketcwav.s3.amazonaws.com/" method="post" enctype="multipart/form-data"> 
    <input id="s3Name" type="hidden" name="key" value="images/${filename}"> 
    <input type="hidden" name="AWSAccessKeyId" value="%accesskey%"> 
    <input type="hidden" name="acl" value="public-read"> 
    <input type="hidden" name="success_action_redirect" value="http://www.mydomain.com/PHP/imageloadsuccess.php"> 
    <input type="hidden" name="policy" value="%policy%" /> 
    <input type="hidden" name="signature" value="%signature%" /> 
    <input id="mimetype" type="hidden" name="Content-Type" value="image/jpeg"> 
    <!-- Include any additional input fields here --> 

    File to upload to S3: 
    <input id="fileinput" name="file" type="file" accept="image/*"> 
    <br> 
    <input type="submit" value="Upload File to S3"> 
</form> 

上傳成功後,http://www.mydomain.com/PHP/imageloadsuccess.php被調用。

現在我試圖做改變我的代碼插入到使用一個XMLHttpRequest,因爲我需要做一些JavaScript圖片大小:

<body> 
<div class="form" id="form"> 
     File to upload to S3: 
     <input id="fileinput" name="file" type="file" accept="image/*"><span id="progress"></span> 
    </form> 

    </div> 
</body> 
<script type="text/javascript"> 
if (window.File && window.FileReader && window.FileList && window.Blob) { 
    document.getElementById('fileinput').onchange = function(event){ 
     var file = event.target.files[0]; // The files selected by the user (as a FileList object entry). 
     event.target.files[0] = resizeAndUpload(event.target.files[0]); 
     }; 
} else { 
     alert('You are using an outdated browser. To get a better site experience, please update your browser to the latest version.'); 
} 

//from http://www.codeforest.net/html5-image-upload-resize-and-crop 
function resizeAndUpload(file) { 
var reader = new FileReader(); 
    reader.onloadend = function() { 

    var tempImg = new Image(); 
    tempImg.src = reader.result; 
    tempImg.onload = function() { 

     var MAX_WIDTH = 1024; 
     var MAX_HEIGHT = 768; 
     var tempW = tempImg.width; 
     var tempH = tempImg.height; 
     if (tempW > tempH) { 
      if (tempW > MAX_WIDTH) { 
       tempH *= MAX_WIDTH/tempW; 
       tempW = MAX_WIDTH; 
      } 
     } else { 
      if (tempH > MAX_HEIGHT) { 
       tempW *= MAX_HEIGHT/tempH; 
       tempH = MAX_HEIGHT; 
      } 
     } 

     var canvas = document.createElement('canvas'); 
     canvas.width = tempW; 
     canvas.height = tempH; 
     var ctx = canvas.getContext("2d"); 
     ctx.drawImage(this, 0, 0, tempW, tempH); 

     // from http://alipman88.github.io/debt/about/index.html 
     var dataURL = canvas.toDataURL("image/jpeg", 0.9); 
     var blob = dataURItoBlob(dataURL); 
     var fd = new FormData(); 

     fd.append("key", "images/"+Math.floor((Math.random()+1)*1000000000000000)+".jpg"); 
     fd.append("AWSAccessKeyId", "%Accesskey%"); 
     fd.append("acl", "public-read"); 
     fd.append("success_action_redirect", "http://www.mydomain.com/PHP/imageloadsuccess.php");  
     fd.append("policy", "%policy%"); 
     fd.append("signature", "%signature%"); 
     fd.append("Content-Type", "image/jpeg"); 
     fd.append("file", blob); 
     var xhr = new XMLHttpRequest(); 
     xhr.open("POST", "https://%bucket%.s3.amazonaws.com/"); 
     xhr.send(fd); 
     } 
    } 
    reader.readAsDataURL(file); 
} 

//helperfunctions 
    //from https://gist.github.com/kosso/4246840 
    function dataURItoBlob(dataURI) { 
     var binary = atob(dataURI.split(',')[1]); 
     var array = []; 
     for(var i = 0; i < binary.length; i++) { 
      array.push(binary.charCodeAt(i)); 
     } 
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); 
} 

// from http://stackoverflow.com/questions/11240127/uploading-image-to-amazon-s3-with-html-javascript-jquery-with-ajax-request-n 
function uploadProgress(evt) { 
    if (evt.lengthComputable) { 
     var percentComplete = Math.round(evt.loaded * 100/evt.total); 
     document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%'; 
    } 
    else { 
     document.getElementById('progressNumber').innerHTML = 'unable to compute'; 
    } 
    } 

</script> 

上載是一樣的成功,除了鉻給我一個錯誤

XMLHttpRequest無法加載http://www.mydomain.com/PHP/imageloadsuccess.php?bucket=bucket&k ... = images%2F1028249253286048.jpg & etag =%226ca24feebab0daf48ffea90d16370868%22。無法從null發出任何請求。

在FF中,此代碼不會給我一個錯誤,但也不會加載imageloadsuccess.php。 我很新的節目,所以我可能沒有看到的東西很簡單在這裏,任何幫助或替代POST方法是極大的讚賞

更新1: 也許這有什麼用它做:https://src.chromium.org/viewvc/blink?revision=155002&view=revision

UPDATE 2:Chrome控制檯確實顯示源爲空,根據http://www.w3.org/TR/cors/#redirect-steps正確無誤。但它不應該阻止它。它是更新1中描述的錯誤。但是也許有人可以告訴我爲什麼使用HTML POST表單在屏幕上實際加載重定向,而只在使用XMLHTTPrequest時在後臺加載?

On POST: 
Request URL:https://%bucket%.s3.amazonaws.com/ 
Request Headersview parsed 
POST https://%bucket%.s3.amazonaws.com/ HTTP/1.1 
Referer: http://%mydomain%.com/test2.html 
Origin: http://%mydomain%.com 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.14 Safari/537.36 

REDIRECT: 
Request URL:http://www.%mydomain%.com/PHP/imageloadsuccess.php?bucket=%bucket%&key=images%2F1851413185242563.jpg&etag=%226ca24feebab0daf48ffea90d16370868%22 
Request Headersview parsed 
GET http://www.%mydomain%.com/PHP/imageloadsuccess.php?bucket=%bucket%&key=images%2F1851413185242563.jpg&etag=%226ca24feebab0daf48ffea90d16370868%22 HTTP/1.1 
**Origin: null** 
Referer: http://%mydomain%.com/test2.html 

更新3: 添加

xhr.onload = function() { console.log(["success", this]) }; 
xhr.onerror = function() { console.log(["error", this]) }; 

顯示在FF和Chrome的錯誤,但兩者實際運行PHP文件。所以看起來一切正常,但我仍然不明白爲什麼會出現這些錯誤。在iOS6 safari中,由於xhr.send(fd),裝載輪繼續旋轉; 我的XMLHTTPrequest一定有問題,但我不知道是什麼。對不起,大量的文字,希望有人看到問題是什麼。

回答

2

我認爲重定向被阻塞是因爲PHP腳本返回的CORS頭文件(它應該使用Access-Control-Allow-Origin: null來響應)。

還有一種替代解決方案。除了使用重定向來通知您的應用程序圖像已上傳之外,您可以在原始S3 POST請求中從success()處理程序中單獨執行AJAX請求(請勿在原始請求中包含success_action_redirect字段/ POST請求成功如果S3響應狀態碼爲200或204)。

+0

向PHP添加'Access-Control-Allow-Origin:null':對於重定向部分非常適用,並不知道這是必需的。 然而,使用success_action_redirect時,初始的POST請求仍然很奇怪:Chrome將POST請求顯示爲「取消」,而iOS6 Safari認爲請求永遠不會完成(加載輪不停地旋轉)。 FF處理得好。 因此,我嘗試了''success_action_status「=」200「'你提到''xhr.onload()'上有一個單獨的AJAX請求,它的作用就像一個魅力!非常感謝,我已經有好幾天了。 – Arjan

+0

不客氣! – dcro