将文件夹上传到 GDrive 并获取用于上传文件的文件夹 ID

Uploading a Folder to GDrive and get the Folder ID to use to upload files

感谢阅读我的问题。我正在 google 驱动器 api 上工作,可以将文件从文本 blob 上传到 google 驱动器。但是,我需要手动添加文件夹 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);
      }
    }
  );
}

我相信你的目标如下。

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

为此,下面的修改模式如何?

模式 1:

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

发件人:

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

收件人:

parents: ['root'],

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

模式二:

当您要创建新文件夹并将文件放入创建的文件夹时,请尝试进行以下修改。不幸的是,在您的脚本中,我不确定您的问题 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);
}

参考: