2017-10-05 45 views
1
$.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形式下载,但被视为类型字符串。我需要一种方法来处理文件,而不是解压缩。有任何想法吗?如何下载和上传zip文件而不保存到磁盘

+7

为什么不干脆做了“获得”后端上的拉链,从给定的URL?会让它更容易 –

+1

为什么你想做这个奇妙的想法?你喜欢有高流量到您的网站? – madalinivascu

+0

@HugoRegibo我有客户端需要这个然后发送到后端服务器。 “获得”的作品,但我得到的数据是二进制的,似乎不再被认为是zip。 –

回答

3

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

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

现在完美运作。在创建新的Blob和新文件时,请记住将数据和blob包装在数组中。谢谢。 –

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"); 
    }); 
}); 
相关问题