如何下载和上传zip文件而不保存到磁盘

时间:2017-10-05 08:52:02

标签: javascript jquery reactjs

 $.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格式下载但看作类型字符串。我需要一种方法来处理文件,就像我的承诺一样,没有解压缩。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以像这样以二进制格式获取数据。

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();

答案 1 :(得分:0)

您可以将回复用作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" );
    } );
} );