2014-02-25 45 views
1

我想在另一個域上發送文件,但progress event不起作用。如果我評論onprogress功能,該文件所上傳的,否則會出現錯誤:如何使用XMLHttpRequest發送跨域的文件?

OPTIONS http://another-domain.com No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.com' is therefore not allowed access. XMLHttpRequest cannot load http://another-domain.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.com' is therefore not allowed access.

下面是代碼:

$("form").on("submit", function(e) { 
    e.preventDefault(); 
    var file = $("#file")[0].files[0]; 

    var fd = new FormData(); 
    fd.append("Filedata", file); 

    var xhr = getXDomainRequest(); 

    xhr.onprogress = function(e) { 
     if (e.lengthComputable) { 
      var percentComplete = (e.loaded/e.total) * 100; 
      console.log(percentComplete + '% uploaded'); 
     } 
    }; 

    xhr.onload = function() { 
     if (this.status == 200) { 
      var resp = JSON.parse(this.response); 
      console.log('Server got:', resp); 
     } 
    }; 

    xhr.open('POST', 'http://another-domain.com', true); 
    xhr.send(fd); 
}); 

function getXDomainRequest() { 
    var xdr = null; 

    if (window.XDomainRequest) 
     xdr = new XDomainRequest();  
    else if (window.XMLHttpRequest) 
     xdr = new XMLHttpRequest();  
    else 
     alert("Cross Domain not supported"); 
               
    return xdr;         
} 

我不能修改another-domain.com因爲它是一個API。

我試圖使用AJAX, File Upload但我不能使用progress事件。

有什麼想法?

編輯

這裏是File Upload

$('#fichier').fileupload({ 
    dataType: "jsonp", // API error 
    beforeSend : function() { 
     $("#upload_progression_pj").show(); 
    }, 
    progress: function (e, data) { 
     var actuel = Math.round(data.loaded * 100/data.total); 
     log(actuel); 
     $("#upload_progression_pj span").html(actuel + "%"); 
    }, 
    done: function (e, data) { 
     $("#upload_progression_pj").hide(); 
     $("#upload_progression_pj span").empty(); 
    } 
}); 
+0

在您的調用中使用'jsonp'作爲'dataType',或者將頭部'Access-Control-Allow-Origin'設置爲適當的值。 – verisimilitude

回答

-1

跨域Ajax另一種解決方案只能使用JSONP,所以這是在你需要尋找的方向來完成。它有大量的在線例子,我不認爲你會發現和實現它的任何問題。

+0

我已經試過這個解決方案,但API不能與jsonp一起使用。所以我不能使用'AJAX',但只能使用HMTL格式? –

+0

但是從你的腳本你已經使用ajax? XMLHttpRequest是ajax?我沒有看到你想說什麼? –

+0

看看我的編輯,dataType:'jsonp'不被API支持。我想知道如果唯一的解決方案是一個正常的HTML表單,因爲我不能顯式使用'jsonp' –

0

如果您使用XHR2跨文件上傳文件,您的服務器需要處理預檢(OPTIONS)請求,瀏覽器在發送底層上傳POST請求之前將發送這些請求。當然,除了這個服務器對於非預先知道的CORS請求的支持之外,這當然也是如此。

XHR2的上傳進度專門觸發預檢,即使上傳POST請求沒有其他要求需要預檢交叉源請求。我stumbled into this a while back myself

如果您無法控制服務器並且不處理OPTIONS /預檢請求,那麼您將無法使用上載進度事件。