2017-10-29 57 views
0

我需要上傳包含標題和特定數字等元數據的zip文件。Javascript在xhttp POST請求中用zip文件發送元數據

要麼我直接發送壓縮文件:

function generalPostRequest(content, url, cb) {  
    var xhttp = new XMLHttpRequest(); 
    xhttp.open("POST", url, true); 
    xhttp.withCredentials = true; 
    xhttp.setRequestHeader("Authorization", "Basic " + btoa("NAME:PASS")); 

    //DIFF 
    xhttp.setRequestHeader("Content-Type", "application/zip"); 
    //DIFF 

    xhttp.onreadystatechange = function() { 
     if (xhttp.readyState === 4 && xhttp.status === 200) { 
      if (cb) { 
       cb(JSON.parse(xhttp.response)); 
      } 
     } 
    }; 
    xhttp.send(content);//DIFF 
} 

但是當時我不知道如何添加元數據。 另一種方法是:

function generalPostRequest(content, url, cb) { 
    var xhttp = new XMLHttpRequest(); 
    xhttp.open("POST", url, true); 
    xhttp.withCredentials = true; 
    xhttp.setRequestHeader("Authorization", "Basic " + btoa("NAME:PASS")); 

    //DIFF 
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
    var params = JSON.stringify(content); 
    //DIFF 

    xhttp.onreadystatechange = function() { 
     if (xhttp.readyState === 4 && xhttp.status === 200) { 
      if (cb) { 
       cb(JSON.parse(xhttp.response)); 
      } 
     } 
    }; 
    xhttp.send(params);//DIFF 
} 

但是,如果我添加了壓縮到一個數組中,JSON.stringify函數刪除的zip文件。我可能不得不將它轉換成一個字節數組。

如何添加元數據方案1或我怎麼轉換壓縮到一個字節數組中的解決方案2?

+0

什麼樣的元數據?說明你需要發送這個元數據的文檔在哪裏?最好的猜測是,您將添加一個自定義標題,如'Authorization'和'Content-Type',但需要首先查看文檔。 – Tigger

+0

我想在一個POST請求中發送一個zip文件,一個數字和一個字符串。沒有文檔。 –

+0

您需要使用FormData。請參閱:[demo/sample/docs](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications)。 – Tigger

回答

0

我沒有真正測試過這個,因爲我不知道content究竟是什麼類型的值,所以很難構建正確的測試用例

您正試圖發送一個JSON文件和壓縮文件中的一個請求。要做到這一點的方法是多部分請求。

XMLHttpRequest可以構建來自FormData對象多部分請求。

您只需要創建一個併爲其提供正確的數據。

var zip_data = get_zip_data(); 
var json_data = get_json_data(); 

var zip_file = new File(zip_data, "example.zip", { type: "application/zip" }); 
var json_file = new File(json_data, "example.json", { type: "application/json" }); 

var form_data = new FormData(); 
form_data.append("zip", zip_file, "example.zip"); 
form_data.append("json", json_file, "example.json"); 

var xhttp = new XMLHttpRequest(); 
xhttp.open("POST", url); 
xhttp.withCredentials = true; 
xhttp.setRequestHeader("Authorization", "Basic " + btoa("NAME:PASS")); 
xhttp.addEventListener("load", load_handler); 
xhttp.send(form_data); 

function load_handler() { 
    if (cb) { 
     cb(JSON.parse(xhttp.response)); 
    } 
} 

請注意,您不得設置Content-Type頭。 XHR將自動從FormData對象中生成它(並且必須這樣做,因爲它需要在文件之間生成邊界標記)。

這將導致這兩個文件就好像你在一個普通形式<input type="file">拿起他們被髮送到服務器。相應地編寫服務器端代碼(例如,如果您使用的是PHP,或者如果使用的是Node.js,則使用$_FILES)。

+0

謝謝你一堆。 –