[英]How to download and upload zip file without saving to disk
$.ajax({
url: 'url.com/myfile.zip',
})
.then((data) => {
const blob = new Blob([parsed_data], {type: 'application/octet-stream'});
const file = new File([blob], filename, {type: 'application/zip'});
this.handleUpload(file); // Sends POST request with received file
});
我正在尝试下载并立即上传一个zip文件。 但是,上传端点不会将接收到的文件识别为zip,尽管它已下载为zip但被视为类型字符串。 我需要一种在不解压缩的情况下按原样处理文件的方法。 有任何想法吗?
您可以像这样以二进制格式获取数据。
xhr.open('GET', 'url.com/myfile.zip', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var data = this.response;
const blob = new Blob(data, {type: 'application/octet-stream'});
const file = new File(blob, filename, {type: 'application/zip'});
this.handleUpload(file); // Sends POST request with received file
}
};
xhr.send();
您可以将响应用作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" );
} );
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.