使用 google Drive api 上传 Excel 文件

Luc*_*olo 3 javascript excel google-api node.js google-drive-api

我在使用 Google Drive API 时遇到问题。

我正在尝试使用此 API 上传 Excel 文件,但它不起作用。即使复制 google API 文档也不起作用。

这是我的代码示例:

@Get('teste')
async teste(){
    const keys = require(path.resolve('src', 'files', 'api', 'keys'))
    const client = new google.auth.JWT(
        keys.client_email,
        null,
        keys.private_key,
        ['https://www.googleapis.com/auth/drive.metadata.readonly']
    )

    client.authorize((err, tokens) =>{
        if(err){
            console.log(err)
            return;
        } else{
            this.gdrun(client)
        }
    })

}

gdrun(client){
    const drive = google.drive({version: 'v3', auth: client});

    var fileMetadata = {
        name: 'My Report',
        mimeType: 'application/vnd.google-apps.spreadsheet'
    };
    var media = {
        mimeType: 'application/vnd.ms-excel',
        body: require(path.resolve('src', 'files', 'excel', 'solargroup.xlsx'))
    };
    drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
    }, function (err, file: any) {
        if (err) {
            // Handle error
            console.error(err);
    } else {
        console.log('File Id:', file.id);
    }
    });
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误: 在此输入图像描述

Tan*_*ike 5

我相信你的目标如下。

  • 您想要将文件(XLSX 文件)上传到服务帐户的 Google 云端硬盘。
  • 您希望使用 Node.js 的 googleapis 服务帐户来实现此目的。
  • 根据您的脚本,我认为您可能想通过转换将 XLSX 文件上传为 Google 电子表格。

修改要点:

  • 当您想要将文件上传到 Google Drive 时,在这种情况下,请使用范围https://www.googleapis.com/auth/drive而不是https://www.googleapis.com/auth/drive.metadata.readonly.
  • 当您想要将 XLSX 文件上传为 XLSX 文件时,mimeType 为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
  • 当你要上传文件时,body: require(path.resolve('src', 'files', 'excel', 'solargroup.xlsx'))无法使用。在这种情况下,请使用body: fs.createReadStream(path.resolve('src', 'files', 'excel', 'solargroup.xlsx')). 我认为您的错误消息可能是由于此原因造成的。
  • 当您想检索上传文件的文件ID时,请修改file.idfile.data.id.

当以上几点反映到您的脚本中时,它会变成如下所示。

修改后的脚本:

从:

const client = new google.auth.JWT(
    keys.client_email,
    null,
    keys.private_key,
    ['https://www.googleapis.com/auth/drive.metadata.readonly']
)
Run Code Online (Sandbox Code Playgroud)

到:

const client = new google.auth.JWT(
    keys.client_email,
    null,
    keys.private_key,
    ['https://www.googleapis.com/auth/drive']  // Modified
)
Run Code Online (Sandbox Code Playgroud)

另外,请gdrun()按如下方式修改您的。

gdrun(client){
  const drive = google.drive({ version: "v3", auth: client });

  var fileMetadata = {
    name: "My Report",
    mimeType: "application/vnd.google-apps.spreadsheet",
  };
  var media = {
    mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",  // Modified
    body: fs.createReadStream(path.resolve('src', 'files', 'excel', 'solargroup.xlsx')),  // Modified
  };
  drive.files.create(
    {
      resource: fileMetadata,
      media: media,
      fields: "id",
    },
    function (err, file) {
      if (err) {
        console.error(err);
      } else {
        console.log("File Id:", file.data.id);  // Modified
      }
    }
  );
}
Run Code Online (Sandbox Code Playgroud)
  • 在这种情况下,请使用const fs = require("fs").

结果:

运行上面的脚本,得到以下结果。

File Id: ###fileId###
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您的脚本将 XLSX 文件作为 Google 电子表格上传到服务帐户的 Google Drive。在这种情况下,您无法直接在 Google 云端硬盘上看到上传的文件。因为服务帐户的 Google Drive 与您的 Google Drive 不同。当您想在 Google 云端硬盘上查看上传的文件时,请在您的 Google 云端硬盘上创建一个文件夹,并将创建的文件夹与服务帐户的电子邮件共享。然后,请将文件上传到共享文件夹。这样,您就可以使用浏览器在 Google Drive 上看到上传的文件了。为此,请进行fileMetadata如下修改。

      var fileMetadata = {
        name: "My Report",
        mimeType: "application/vnd.google-apps.spreadsheet",
        parents: ["### folderId ###"],  // Please set the folder ID of the folder shared with the service account.
      };
    
    Run Code Online (Sandbox Code Playgroud)
  • 在上面的脚本中,最大文件大小为 5 MB。请小心这一点。当您要上传超过5MB的文件时,请使用断点续传。参考号

参考: