【问题标题】:Uploading a Folder to GDrive and get the Folder ID to use to upload files将文件夹上传到 GDrive 并获取用于上传文件的文件夹 ID
【发布时间】:2020-07-16 17:48:24
【问题描述】:

感谢您阅读我的问题。我正在研究 google drive api,可以将文件从文本 blob 上传到 google drive。但是,我需要手动添加文件夹 ID,以便用户使用它并且不会出现错误,因为他们正在尝试将其上传到 my 文件夹中。如何创建或仅获取文件夹 ID - 甚至可以上传到 GDrive 根目录?任何提示都会有所帮助。

谢谢

// Global vars
const SCOPE = 'https://www.googleapis.com/auth/drive.file';
const gdResponse = document.querySelector('#response');
const login = document.querySelector('#login');
const authStatus = document.querySelector('#auth-status');
const textWrap = document.querySelector('.textWrapper');
const addFolder = document.querySelector('#createFolder');
const uploadBtn = document.querySelector('#uploadFile');

// Save Button and Function
uploadBtn.addEventListener('click', uploadFile);

window.addEventListener('load', () => {
  console.log('Loading init when page loads');
  // Load the API's client and auth2 modules.
  // Call the initClient function after the modules load.
  gapi.load('client:auth2', initClient);
});

function initClient() {
  const discoveryUrl =
    'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

  // Initialize the gapi.client object, which app uses to make API requests.
  // Get API key and client ID from API Console.
  // 'scope' field specifies space-delimited list of access scopes.
  gapi.client
    .init({
      apiKey: 'My-API-Key',
      clientId:
        'My-Client-ID',
      discoveryDocs: [discoveryUrl],
      scope: SCOPE,
    })
    .then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);


// Actual upload of the file to GDrive
function uploadFile() {
  let accessToken = gapi.auth.getToken().access_token; // Google Drive API Access Token
  console.log('Upload Blob - Access Token: ' + accessToken);

  let fileContent = document.querySelector('#content').value; // As a sample, upload a text file.
  console.log('File Should Contain : ' + fileContent);
  let file = new Blob([fileContent], { type: 'application/pdf' });
  let metadata = {
    name: 'Background Sync ' + date, // Filename
    mimeType: 'text/plain', // mimeType at Google Drive

    // For Testing Purpose you can change this File ID to a folder in your Google Drive
    parents: ['Manually-entered-Folder-ID'], // Folder ID in Google Drive
     // I'd like to have this automatically filled with a users folder ID
  };

  let form = new FormData();
  form.append(
    'metadata',
    new Blob([JSON.stringify(metadata)], { type: 'application/json' })
  );
  form.append('file', file);

  let xhr = new XMLHttpRequest();
  xhr.open(
    'post',
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'
  );
  xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
  xhr.responseType = 'json';
  xhr.onload = () => {
    console.log(
      'Upload Successful to GDrive: File ID Returned - ' + xhr.response.id
    ); // Retrieve uploaded file ID.
    gdResponse.innerHTML =
      'Uploaded File. File Response ID : ' + xhr.response.id;
  };
  xhr.send(form);
}

我没有包括一些不相关的东西。我有这样的东西用于上传文件夹,但不出所料。

function createFolder() {
  var fileMetadata = {
    name: 'WordQ-Backups',
    mimeType: 'application/vnd.google-apps.folder',
  };
  drive.files.create(
    {
      resource: fileMetadata,
      fields: 'id',
    },
    function (err, file) {
      if (err) {
        // Handle error
        console.error(err);
      } else {
        console.log('Folder Id: ', file.id);
      }
    }
  );
}

【问题讨论】:

    标签: javascript google-api google-drive-api google-api-js-client


    【解决方案1】:

    我相信你的目标如下。

    • 您想将文件上传到根文件夹或创建的新文件夹。

    为此,下面的修改模式怎么样?

    模式一:

    当你想把文件放到根文件夹时,请尝试以下修改。

    发件人:

    parents: ['Manually-entered-Folder-ID'],
    

    收件人:

    parents: ['root'],
    

    或者,请删除parents: ['Manually-entered-Folder-ID'],。这样,文件就会创建到根文件夹。

    模式 2:

    当你想创建新文件夹并将文件放入创建的文件夹时,请尝试以下修改。不幸的是,在您的脚本中,我从您的问题中不确定createFolder() 中的drive。所以我无法理解您的createFolder() 的问题。所以在这个模式中,文件夹是用XMLHttpRequest创建的。

    修改脚本:

    function createFile(accessToken, folderId) {
      console.log('File Should Contain : ' + fileContent);
      let fileContent = document.querySelector('#content').value;
      console.log('File Should Contain : ' + fileContent);
      let file = new Blob([fileContent], { type: 'application/pdf' });
    
      let metadata = {
        name: 'Background Sync ' + date,
        mimeType: 'text/plain',
        parents: [folderId], // <--- Modified
      };
      let form = new FormData();
      form.append(
        'metadata',
        new Blob([JSON.stringify(metadata)], { type: 'application/json' })
      );
      form.append('file', file);
      
      let xhr = new XMLHttpRequest();
      xhr.open(
        'post',
        'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'
      );
      xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
      xhr.responseType = 'json';
      xhr.onload = () => {
        console.log(
          'Upload Successful to GDrive: File ID Returned - ' + xhr.response.id
        );
        gdResponse.innerHTML =
          'Uploaded File. File Response ID : ' + xhr.response.id;
      };
      xhr.send(form);
    }
    
    function createFolder(accessToken) {
      const folderName = "sample"; // <--- Please set the folder name.
      
      let metadata = {
        name: folderName,
        mimeType: 'application/vnd.google-apps.folder'
      };
      let xhr = new XMLHttpRequest();
      xhr.open('post', 'https://www.googleapis.com/drive/v3/files?fields=id');
      xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.responseType = 'json';
      xhr.onload = () => {
        const folderId = xhr.response.id;
        console.log(folderId);
        createFile(accessToken, folderId);
      };
      xhr.send(JSON.stringify(metadata));
    }
    
    // At first, this function is run.
    function uploadFile() {
      let accessToken = gapi.auth.getToken().access_token;
      createFolder(accessToken);
    }
    

    参考:

    【讨论】:

    • 正是我想要的。谢谢!
    • @matt 感谢您的回复。很高兴您的问题得到解决。
    • 没问题,我周末在小屋里,抱歉耽搁了。我不是一个大堆栈溢出用户,所以如果我错过了给你积分或者我道歉。我赞成并选择您的答案作为正确的解决方案
    • @matt 非常感谢您的支持!
    猜你喜欢
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多