Google 驱动器 API - 使用 JSZip 获取文件和压缩返回损坏的文件

Google Drive API - Get file and zip with JSZip is returning corrupt file

我正在使用 Google Drive's API to get the BLOB of a file and attempting to give that BLOB data to JSZip 压缩,但遇到问题。

具体代码段如下所示:

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://www.googleapis.com/drive/v3/files/"+file_id+"?alt=media",
    "method": "GET",
    "headers": {
        "responseType": "blob",
        "Authorization": "Bearer "+bearer_token
     }
}

$.ajax(settings).done(function (response, status, xhr) {
    console.log(response);
    zip.file(filename, response);

    zip.generateAsync({type:"blob"}, function updateCallback(metadata) {
        var msg = "progression : " + metadata.percent.toFixed(2) + " %";
        if(metadata.currentFile) {
            msg += ", current file = " + metadata.currentFile;
        }
        showMessage(msg);
        updatePercent(metadata.percent|0);
     })
     .then(function callback(blob) {
         saveAs(blob, "example.zip");
         showMessage("done !");
     }, function (e) {
         showError(e);
     });
 });

我使用 Postman 进行了 API 测试,返回了预期的结果。我试过压缩几个 image/pdf/zip 文件,所有这些文件都已损坏。到目前为止唯一有用的是 PHP 文件。 Google 驱动器 API 正在正确返回 BLOB 数据,并且在 JSZip 生成的 zip 文件(文件名、文件大小等)中一切看起来都是正确的,但是从 zip 打开文件时,我收到错误提示文件已损坏。

有什么想法吗?

提前感谢您的帮助!

  • 您想从 Google 驱动器中检索一个 zip 文件。
  • 您想使用 Javascript 实现此目的。
  • 您已经能够使用驱动器 API 获取和放置文件。

如果我的理解是正确的,这个修改怎么样?

修改点:

  • 我认为您的问题的原因是 zip 文件被检索为字符串数据。
    • 对于这种情况,我使用了fetch

修改后的脚本:

请修改如下

从:
var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://www.googleapis.com/drive/v3/files/"+file_id+"?alt=media",
    "method": "GET",
    "headers": {
        "responseType": "blob",
        "Authorization": "Bearer "+bearer_token
     }
}

$.ajax(settings).done(function (response, status, xhr) {
到:
const url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media";
fetch(url, {
  method: "GET",
  dataType: "binary",
  responseType: "blob",
  headers: {Authorization: "Bearer " + bearer_token},
  // crossDomain: true, // This might not be required.
})
.then(res => res.blob())
.then(response => {
  • 在上面修改的脚本中,response 是一个 blob。
  • 请设置file_idbearer_token

用于测试:

作为测试样例脚本,下面的脚本怎么样?当您运行此脚本时,下载的zip文件将作为sample.zip的文件名保存到本地PC。我认为该脚本可能可以使用此脚本进行测试。

const url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media";
fetch(url, {
  method: "GET",
  dataType: "binary",
  responseType: "blob",
  headers: {Authorization: "Bearer "+bearer_token},
})
.then(res => res.blob())
.then(blob => {
  var a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.target = "_blank";
  a.download = "sample.zip";
  a.click();
});

注:

  • 这是一个简单的示例脚本。所以请根据您的情况修改此内容。

参考文献:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。