如何使用Google Drive API和Javascript删除符合条件的文件列表? [英] How do I delete a list of files meeting criteria with Google Drive API and Javascript?

查看:217
本文介绍了如何使用Google Drive API和Javascript删除符合条件的文件列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用获取列表(我已经编码)获取列表,但接下来,我想要一个删除按钮,删除列表中的所有内容。如何使用Google Drive SDK和Javascript来做到这一点?



例如,如果我的标准是:

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

如何删除符合该条件的每个文件?

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



我试过拟合搜索文件和一起删除文件,但我真的很糟糕,我不确定哪个变量代表所有符合条件的文件以及如何将该变量设置为fileID:

 函数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<'+ (函数deleteFile(fileId))返回一个字符串,如下所示:

$ b字段:nextPageToken,files(id),
}

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


解决方案

,您将首先向 GET nofollow noreferrer> files endpoint,使用支持查询参数 q list 操作。这听起来像你已经有了这个想法。



你会得到一个响应对象 - 为了得到更具体的,你需要发布一些代码。您是否使用了VanillaJS XMLHttpRequest ,jQuery的 $。ajax(),或许是美味的本地异步 fetch() API?无论采用哪种方式,您都会得到可以解析为JSON的响应。

正如您发现的,Drive API不支持在一个请求中永久删除多个Drive资源。此时,您可能正在重新思考应用程序的体系结构:删除很长的列表可能需要很多HTTP请求。这可能会产生很大的开销,所以你可能想要限制列表的长度或者做一些其他的事情。如果你决定采用这种方式,我建议使用 fetch 来异步使用API​​。

如果您使用的是<$ c $>,请调用 JSON.parse(responseBody)(或 responseBody.json() c> fetch()),您将从Google API获得如下所示的内容:

  {
kind:drive#fileList,
etag:...,
selfLink:https://www.googleapis.com/drive/ v2 / files,
nextPageToken:...,
nextLink:...,
incompleteSearch:false,
items :[
{
kind:drive#file,
id:某些文件ID,
etag:...,
selfLink:...,
alternateLink:...,
embedLink:...,
openWithLinks:{
...
},
{
kind:drive#file,
id:某些文件ID,
etag:...,
selfLink:...,
alternateLink:...,
embedLink:... ,
openWithLi nks:{
...
}
]

所以你需要的是:


  1. 一个函数:


    • 在您的 GET 到files.list完成时调用。 循环 responseJSON.items ,并用itemId调用下面的函数。


  2. 一个 HTTP DELETE 给出一个ID。


您的实施的具体细节,为您的目的的一般解决方案可能如下所示:

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

//在一个汇编GET查询字符串好的方法
Object.keys(params).forEach(function(key){
apiEndpoint.searchParams.append(key,params [key]);
});

//去取! (明确的HTTP头选项可选,但很好的做法)
fetch(apiEndpoint,{
method:'GET',
mode:'cors',
redirect:'follow',
标题:新标题({
'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);
}
});

});

函数asyncDeleteDriveItem(){/ * ... * /}


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. How can I do that with Google Drive SDK and 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

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:

 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. 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? Either way, you will get a response which can be parsed to JSON.

As you have discovered, the Drive API does not support permanently deleting multiple Drive resources in one request. At this point, you may be rethinking the architecture of your application: removing a very long list could require many HTTP requests. 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.

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:

{
 "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.
    • Loops through responseJSON.items and calls the function below with an itemId.
  2. A function which issues an HTTP DELETE given an ID.

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() {/* ... */}

这篇关于如何使用Google Drive API和Javascript删除符合条件的文件列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆