我需要上傳包含標題和特定數字等元數據的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?
什麼樣的元數據?說明你需要發送這個元數據的文檔在哪裏?最好的猜測是,您將添加一個自定義標題,如'Authorization'和'Content-Type',但需要首先查看文檔。 – Tigger
我想在一個POST請求中發送一個zip文件,一個數字和一個字符串。沒有文檔。 –
您需要使用FormData。請參閱:[demo/sample/docs](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications)。 – Tigger