javascript - Google Drive API 和从浏览器上传文件

标签 javascript google-api google-drive-api

我正在尝试使用 Google Drive API 上传一个文件,我的元数据是正确的,我想确保实际的文件内容在那里。我有一个简单的页面设置,如下所示:

<div id="upload">
  <h6>File Upload Operations</h6>
  <input type="file" placeholder='file' name='fileToUpload'>
  <button id='uploadFile'>Upload File</button>
</div>

我有一个 javascript 设置,提示用户先登录,然后他们可以上传文件。这是代码:(目前只上传文件元数据....)

let uploadButton = document.getElementById('uploadFile');
uploadButton.onclick = uploadFile;
const uploadFile = () => {
    let ftu = document.getElementsByName('fileToUpload')[0].files[0];
    console.dir(ftu);
    gapi.client.drive.files.create({
        'content-type': 'application/json;charset=utf-8',
        uploadType: 'multipart',
        name: ftu.name,
        mimeType: ftu.type,
        fields: 'id, name, kind'
    }).then(response => {
        console.dir(response);
        console.log(`File: ${ftu.name} with MimeType of: ${ftu.type}`);
        //Need code to upload the file contents......
    });
};

首先,我更熟悉后端,所以从 <input type='file'> 中以位的形式获取文件标签对我来说有点模糊。从好的方面来说,元数据就在那里。如何获取文件内容到 api?

最佳答案

因此,根据我在为期三天的搜索中找到的一些资源,该文件根本无法通过 gapi 客户端上传。它必须通过真正的 REST HTTP 调用上传。那么让我们使用fetch吧!

const uploadFile = () => {
    //initialize file data from the dom
    let ftu = document.getElementsByName('fileToUpload')[0].files[0];
    let file = new Blob([ftu]); 
    //this is to ensure the file is in a format that can be understood by the API

    gapi.client.drive.files.create({
        'content-type': 'application/json',
        uploadType: 'multipart',
        name: ftu.name,
        mimeType: ftu.type,
        fields: 'id, name, kind, size'
    }).then(apiResponse => {
        fetch(`https://www.googleapis.com/upload/drive/v3/files/${response.result.id}`, {
         method: 'PATCH',
         headers: new Headers({
             'Authorization': `Bearer ${gapi.client.getToken().access_token}`,
              'Content-Type': ftu.type
         }),
         body: file
       }).then(res => console.log(res));

}

授权 header 是通过调用 gapi.client.getToken().access_token 函数分配的,基本上这从 gapi 调用的响应中获取空对象并调用 fetch 用于上传文件的实际位的 api!

关于javascript - Google Drive API 和从浏览器上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839499/

相关文章:

javascript - 映射两个数组以查看一个属性是否匹配,然后将特定信息推送到第一个数组中

javascript - 如何在 ReactJS 的同一个类中调用方法?

oauth - Google+ 互动帖子不起作用?

google-maps - 在Google开发者控制台的 "Accept requests from these HTTP referrers"字段中设置HTTP引用的正确方法

google-apps-script - Google 云端硬盘第三方快捷方式的工作原理

javascript - 无限 asyncIterator 未按预期工作

javascript - 当从 csv 更新数据时,d3 在 setInterval 上闪烁文本

google-api - 在哪里生成 Google+ 登录 API 防请求伪造状态 token ?

google-drive-api - 向服务帐户授予域范围的权限

php - 视网膜图标与 Google Drive API 的链接