简体   繁体   English

如何使用Google Drive API和Javascript删除符合条件的文件列表?

[英]How do I delete a list of files meeting criteria with Google Drive API and Javascript?

I want to get a list of things with get list (which I have already coded in), but next, I want a delete button that deletes all the things on that list. 我想使用get list(已经在其中进行编码)获取事物列表,但是接下来,我想要一个Delete按钮,用于删除该列表中的所有事物。 How can I do that with Google Drive SDK and Javascript? 如何使用Google Drive SDK和Javascript做到这一点?

Example, if my criteria is: 例如,如果我的标准是:

 q: "starred = "+test+" and viewedByMeTime < '"+n+""

How do I delete every single file that meets that criteria? 如何删除符合该条件的每个文件?

References: https://developers.google.com/drive/v2/reference/files/delete https://developers.google.com/drive/v2/web/search-parameters 参考: https : //developers.google.com/drive/v2/reference/files/delete https://developers.google.com/drive/v2/web/search-parameters

I tried fitting search file and delete files together, but I am really bad at it and I am not sure which variable represents all the files found matching the criteria and how to get that variable to be fileID: 我尝试将搜索文件和删除文件放在一起,但是我真的很不好,而且我不确定哪个变量代表所有符合条件的文件,以及如何使该变量成为fileID:

 function DeleteFiles() {
var x = document.getElementById("ResultShown").value;


var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0] ;
  var test = false;

    gapi.client.drive.files.list({

      pageSize: x,
     q: "starred = "+test+" and viewedByMeTime < '"+n+"'",


      fields: "nextPageToken, files(id)",
     }

    ).then(function deleteFile(fileId)) {
  var request = gapi.client.drive.files.delete({
  appendPre('Files:');
      var files = response.result.files;
      if (files && files.length > 0) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
'fileId': fileId
  });
     request.execute(function(resp) { })
        }
      } 
    });
  }

So using the Javascript Drive API, you will first issue a GET to the files endpoint, using the list action which supports your query parameter q . 因此,使用Javascript Drive API,您将首先使用支持查询参数qlist操作向文件端点发出GET It sounds like you already have that figured out. 听起来您已经知道了。

You will get a response object -- to get more specific, you would need to post some code. 您将获得一个响应对象-为了更具体,您将需要发布一些代码。 Are you using VanillaJS XMLHttpRequest , jQuery's $.ajax() , perhaps the delicious and native async fetch() API? 您是否正在使用VanillaJS XMLHttpRequest ,jQuery的$.ajax() ,也许是美味而本地的异步fetch() API? Either way, you will get a response which can be parsed to JSON. 无论哪种方式,您都会获得一个可以解析为JSON的响应。

As you have discovered, the Drive API does not support permanently deleting multiple Drive resources in one request. 如您所知,Drive API不支持在一个请求中永久删除多个Drive资源。 At this point, you may be rethinking the architecture of your application: removing a very long list could require many HTTP requests. 此时,您可能正在重新考虑应用程序的体系结构:删除很长的列表可能需要许多HTTP请求。 This could generate significant overhead, so you might want to limit how long lists can be or do something else clever. 这可能会产生大量开销,因此您可能想要限制列表的长度或执行其他更聪明的操作。 If you decide to take this route, I'd suggest using fetch to use the API asynchronously. 如果您决定采用这种方法,建议您使用fetch异步使用API​​。

So after you call JSON.parse(responseBody) (or responseBody.json() if you're using fetch() ), you will get something from Google API that looks like this: 所以,你打电话后JSON.parse(responseBody)responseBody.json()如果你使用fetch() ),你会得到谷歌的API,它看起来是这样的:

{
 "kind": "drive#fileList",
 "etag": "...",
 "selfLink": "https://www.googleapis.com/drive/v2/files",
 "nextPageToken": "...",
 "nextLink": "...",
 "incompleteSearch": false,
 "items": [
  {
   "kind": "drive#file",
   "id": "SOME FILE ID",
   "etag": "...",
   "selfLink": "...",
   "alternateLink": "...",
   "embedLink": "...",
   "openWithLinks": {
        ...
   },
   {
   "kind": "drive#file",
   "id": "SOME FILE ID",
   "etag": "...",
   "selfLink": "...",
   "alternateLink": "...",
   "embedLink": "...",
   "openWithLinks": {
        ...
   }
]

So what you need is: 因此,您需要的是:

  1. A function which: 一个功能:

    • Is called when your GET to files.list is complete. 当您完成到files.list的GET时调用。
    • Loops through responseJSON.items and calls the function below with an itemId. 遍历responseJSON.items并使用itemId调用下面的函数。
  2. A function which issues an HTTP DELETE given an ID. 发出给定ID的HTTP DELETE函数。

So without any specific details of your implementation, a general solution for your purpose might look like: 因此,在没有实现的任何具体细节的情况下,针对您目的的通用解决方案可能类似于:

var apiEndpoint = new URL("https://www.googleapis.com/drive/v2/files"),
    params = {q: "some stuff", otherParams: "lol"}

// assemble GET querystring in a nice way
Object.keys(params).forEach(function(key) {
   apiEndpoint.searchParams.append(key, params[key]);
});

// go and fetch! (explicit HTTP header options optional but good practice)
fetch(apiEndpoint , {
                 method: 'GET',
                 mode: 'cors',
                 redirect: 'follow',
                 headers: new Headers({
                     'Content-Type': 'application/json'
                 })
             });
                 .then(function (responseBody) {
                     return responseBody.json();
                 })
                 .then(function (responseObj) {
                     for(i=0; i<responseObj.items.length; i++) {
                         asyncDeleteDriveItem(responseObj.items[i].id);
                     }
                 });

        });

function asyncDeleteDriveItem() {/* ... */}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Drive API:如何列出共享文件夹中的所有文件? - Google Drive API: How do I list all files in a shared folder? Google云端硬盘-列出文件-Javascript - Google Drive - List Files - Javascript google drive api,javascript列表文件什么都不返回 - google drive api, javascript list files returns nothing 如何在 javascript 和 axios 中使用 api 删除多个文件夹? - how to delete multiple folders using google drive api in javascript with axios? 如何使用 Google Drive V3 从共享文件夹中删除文件? - How do I delete files from a shared folder using Google Drive V3? 如何通过Google云端硬盘Javascript OAuth2 API创建Google表格文档? - How do I create a Google Sheets document via the Google Drive Javascript OAuth2 API? 如何使用Google Drive API用Javascript下载文件 - How to use Google Drive API to download files with Javascript Google Drive SDK - JavaScript:如何列出共享文件(不与我共享) - Google Drive SDK - JavaScript : How to list SHARED FILES (not shared with me) 如何在流星上使用Google Drive API上传文件? - How do I upload files via using Google Drive API on meteor? 如何使用 Google Drive API Javascript 列出特定文件夹中的更改 - How to list changes in a specific folder using Google Drive API Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM