【问题标题】:Convert google drive picker file to javascript file type将谷歌驱动器选择器文件转换为 javascript 文件类型
【发布时间】:2021-04-29 02:50:27
【问题描述】:

我正在使用 Google API V3。我有一个场景,我使用谷歌驱动器选择器从驱动器中选择一个文件(任何扩展名)并将其发送到服务器进行操作(由于与项目相关的机密信息,无法提及很多细节)。

编辑:我正在尝试使用驱动器选择器从谷歌驱动器中选择一个 mpp 文件(MS Project)并将该文件发送到服务器。服务器将 MPP 文件转换为 JSON 并将其返回给客户端,这就是我想要做的。我可以使用普通的输入标签来实现这一点,但要求是使用谷歌驱动器选择器。

我能够通过选择器获取文件,使用 Google 文件 API (files.get) 获取文件详细信息,但我不知道进一步将其转换为 JavaScript 文件类型(类似于输入标签我们上传一个文件)。

    showDrivePicker({
        title: 'Pick an mpp file',
        selectFolderEnabled: true,
        enableMyDrive: true
    }, function pickerCallback( data ) {
        if ( data[google.picker.Response.ACTION] == google.picker.Action.PICKED ) {
            var doc = data[google.picker.Response.DOCUMENTS][0],
                url = doc[google.picker.Document.URL].split('/view'),
                name = doc.name;

            gapi.client.files.get({
                  fileId: 'xxxxx', 
                  corpora: 'teamDrive',
                  supportsTeamDrives: true,
                  includeTeamDriveItems: true,
                  includeTeamDriveItemsRequired: true,
                  includeItemsFromAllDrives: true,
                  fields: '*',
            }).then((response) => {
               // I have the downloadUrl here, but what should I do with it?
            })
        }
    }, me);

请帮助解决这个问题。

谢谢

【问题讨论】:

  • 我想这会回答你的问题:stackoverflow.com/questions/60839431/…。基本上将alt: 'media' 添加到get 选项中,response.body 将包含文件的二进制文件。
  • 添加 alt:media 为我提供了文件的二进制文件,但是当我将响应转换为 JavaScript 文件类型并将其发送到服务器时,它无法详细说明数据不是预期的类型.
  • 现在我有了文件的二进制文件,如何将其转换为正确的文件类型?
  • 您要下载和上传什么?

标签: javascript file google-api google-drive-api blob


【解决方案1】:

在这种情况下,你想做的是:

  1. 从驱动器下载文件
  2. 将其转换为 File 对象

您可以通过提供 ID 并将 alt 设置为 media 来下载文件。要创建文件,请使用响应的正文以及原始选择器文档信息中的文件名和 MIME 类型调用其构造函数:

function pickerCallback(data) {
 if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED) {
   const doc = data[google.picker.Response.DOCUMENTS][0]
   gapi.client.drive.files.get({
     fileId: doc.id,
     alt: 'media',
   }).then(function(res) {
     const file = new File([res.body], doc.name, { type: doc.mimeType })
    
     // Do whatever with the file
     console.log(file)
   })
 }
}

参考文献

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多