可以使用响应作为blob
,如在MDN说明。
/**
* Downloading the file
*
* @param {string} file - The url of the target file
* @param callback - Callback for when we are ready
*/
function download(file, callback) {
const request = new XMLHttpRequest();
request.open("GET", file, true);
request.responseType = "arraybuffer";
request.onreadystatechange =() => {
/** Do nothing if we are not ready yet */
if (request.readyState !== XMLHttpRequest.DONE) { return; }
if (request.status === 200) {
callback(new Blob([request.response], { type : "application/zip" }));
} else {
console.error(request.status);
callback(false);
}
};
request.send();
}
然后,对于上传(通常)你使用FormData。
/**
* Uploading the file
* @param {Blob} blob. - A blob of file
* @param {string} filename - The file name
* @param {string} url. - The upload rest point
* @param callback - Callback for when we are ready
*/
function upload(blob, filename, url, callback) {
const formData = new FormData(),
request = new XMLHttpRequest();
/** Configure the request */
request.open("POST", url, true);
formData.append("file", blob, filename);
/** Sets the callback */
request.onreadystatechange =() => {
/** Do nothing if we are not ready yet */
if (request.readyState !== XMLHttpRequest.DONE) { return; }
/** Sends back the response */
if (request.status === 200) {
callback(true);
} else {
console.error(request.status);
callback(false);
}
};
/** Send the request */
request.send(formData);
}
全部放在一起:
download("/uploads/file.zip", function(blob) {
upload(blob, "file.zip", "/api/upload", function(success) {
console.log(success ? "File was uploaded" : "Error occurred");
});
});
为什么不干脆做了“获得”后端上的拉链,从给定的URL?会让它更容易 –
为什么你想做这个奇妙的想法?你喜欢有高流量到您的网站? – madalinivascu
@HugoRegibo我有客户端需要这个然后发送到后端服务器。 “获得”的作品,但我得到的数据是二进制的,似乎不再被认为是zip。 –