2012-04-25 143 views
29

需要关于通过api插入文件到谷歌驱动器的帮助。为此目的的api文档没有清楚地解释如何通过http post请求发送文件的实际主体。如何通过API向Google云端硬盘添加/创建/插入文件?

+0

你在用什么语言工作?你能添加一个链接到相关的API文档吗? – jsbueno 2012-04-25 14:24:41

+1

感谢您的回答。我所指的链接是https://developers.google.com/drive/v1/reference/files/insert。 – Niranja 2012-04-25 14:31:58

+0

你在用什么语言?我们有几个例子。 – 2012-04-25 15:14:57

回答

58

documentation on insert operations已经包含了很多编程语言的例子,下面介绍如何使用Google Drive API的基于HTTP的协议来实现。

首先,将新文件元数据POST到驱动器端点。它是在一个File resource JSON object形式:

POST /drive/v2/files HTTP/1.1 
Host: www.googleapis.com 
Authorization: Bearer <OAuth 2.0 access token here> 
... 

{ 
    "title": "file_name.extension", 
    "mimeType": "mime/type", 
    "description": "Stuff about the file" 
} 

响应体将是新创建的文件资源的JSON表示。它将如下所示:

{ 
    "kind": "drive#file", 
    "id": string, 
    "etag": etag, 
    "selfLink": string, 
    "title": "file_name", 
    "mimeType": "mime/type", 
    "description": "Stuff about the file" 
    ... 
    "downloadUrl": string, 
    ... 
} 

这是确认已创建文件条目。现在您需要上传内容。为此,您需要在上述响应中获取ID为 JSON属性给出的文件的ID,并使用OAuth 2.0授权请求将实际文件的内容放入上载端点。它应该看起来像:

PUT /upload/drive/v2/files/{id}?uploadType=media HTTP/1.1 
Host: www.googleapis.com 
Authorization: Bearer <OAuth 2.0 access token here> 
Content-Type: mime/type 

<file content here> 

你完成了:)

还有一种方式,1个单POST请求做到这一点使用您发布该文件的元数据在同一时间multipart请求作为内容。下面是一个示例:

POST /upload/drive/v2/files HTTP/1.1 
Host: www.googleapis.com 
Authorization: Bearer <OAuth 2.0 access token here> 
Content-Type: multipart/form-data; boundary=287032381131322 
... 

--287032381131322 
Content-Type: application/json 

{ 
    "title": "file_name.extension", 
    "mimeType": "mime/type", 
    "description": "Stuff about the file" 
} 
--287032381131322 
Content-Type: mime/type 

<file content here> 
--287032381131322-- 

响应将包含新创建的文件的元数据。 您也可以使用请求的子部分中的Content-Transfer-Encoding:base64标头,以便能够将文件的数据作为Base 64编码传递。

最后还有一个resumable upload protocol这是方便上传大文件,提供暂停/恢复功能和/或上传与片状互联网连接的文件。

PS:大部分现在描述在Drive's file upload documentation

+0

谢谢尼古拉斯。你的解决方案帮助我了解情况。实际上没有提到将文件内容发送到下载网址的第二部分。但现在我面临一个新问题,那就是当我尝试发布文件元数据时,我收到一条错误消息,说“经过身份验证的用户未安装带客户端ID的应用程序”。你能帮我解决这个问题吗? – Niranja 2012-04-26 07:06:08

+0

Niranja>在Google Drive环境中,如果用户安装了应用程序(通过OAuth 2流程不够),Google Drive应用程序只能访问用户的Drive。要进行开发,您必须创建启用了云端硬盘的Chrome网上应用店列表(请参阅https://developers.google.com/drive/listing)并进行安装。 – Nivco 2012-04-26 07:34:44

+0

哦,我错过了。再次感谢。实际上,我认为它与创建Facebook应用程序时所遵循的过程类似,并没有在文档中阅读更多信息。 – Niranja 2012-04-26 07:50:35

16

感谢您的解释!这花了我几个小时的时间在蹩脚的谷歌软件开发工具包文档中圈出(对不起,我不得不把我的咆哮)。

这是我提出,将更新一个文本文件(你可以看到我更新HTML)的函数:

function gd_updateFile(fileId, folderId, text, callback) { 

    const boundary = '-------314159265358979323846'; 
    const delimiter = "\r\n--" + boundary + "\r\n"; 
    const close_delim = "\r\n--" + boundary + "--"; 

    var contentType = "text/html"; 
    var metadata = {'mimeType': contentType,}; 

    var multipartRequestBody = 
     delimiter + 'Content-Type: application/json\r\n\r\n' + 
     JSON.stringify(metadata) + 
     delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' + 
     text + 
     close_delim; 

    if (!callback) { callback = function(file) { console.log("Update Complete ",file) }; } 

    gapi.client.request({ 
     'path': '/upload/drive/v2/files/'+folderId+"?fileId="+fileId+"&uploadType=multipart", 
     'method': 'PUT', 
     'params': {'fileId': fileId, 'uploadType': 'multipart'}, 
     'headers': {'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'}, 
     'body': multipartRequestBody, 
     callback:callback, 
    }); 
    } 

这是谷歌的例子的混搭(从上传使用二进制文件) ,以及上面的@Nivco的很好的解释。

+12

+1让咆哮出 – 2013-04-04 12:27:33

7

4年后,这仍然很难弄清楚。我拿@ user1158023的答案来支持上传图片。 我使用API​​ v3和superagent.js来帮助我(因为gapi.client.request发送请求到content.googleapis.com !?)。希望有人可能会觉得这很有用。

function gd_uploadFile(name, contentType, data, callback) { 
    const boundary = '-------314159265358979323846'; 
    const delimiter = "\r\n--" + boundary + "\r\n"; 
    const close_delim = "\r\n--" + boundary + "--"; 

    contentType = contentType || "text/html"; 
    var metadata = { 
     name: name, 
     'mimeType': contentType 
    }; 

    var multipartRequestBody = 
     delimiter + 'Content-Type: application/json\r\n\r\n' + 
     JSON.stringify(metadata) + 
     delimiter + 
     'Content-Type: ' + contentType + '\r\n'; 

    //Transfer images as base64 string. 
    if (contentType.indexOf('image/') === 0) { 
     var pos = data.indexOf('base64,'); 
     multipartRequestBody += 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + 
      data.slice(pos < 0 ? 0 : (pos + 'base64,'.length)); 
    } else { 
     multipartRequestBody += + '\r\n' + data; 
    } 
    multipartRequestBody += close_delim; 

    if (!callback) { callback = function(file) { console.log("Update Complete ", file) }; } 

    superagent.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'). 
     set('Content-Type', 'multipart/form-data; boundary="' + boundary + '"'). 
     set('Authorization', 'Bearer ' + gapi.auth.getToken().access_token). 
     send(multipartRequestBody). 
     end(function() { 
      console.log(arguments); 
     }); 
} 

//On upload 
$('#file')[0].onchange = function() { 
    var file = $('#file')[0].files[0]; 
    if (file && file.type === 'image/jpeg') { 
     var reader = new FileReader(); 
     reader.onloadend = function() { 
      var data = reader.result; 
      gd_uploadFile('img.jpg', 'image/jpeg', data, function() { 
       console.log(arguments); 
      }); 
     } 
     reader.readAsDataURL(file); 
    } 
}; 

索引。HTML

... 
<form> 
    <span>Upload: </span><input id="file" type="file" name="myFile"> 
</form> 
... 
+0

这救了我!非常感谢您的先生!是否可以指定一个应该上传到元数据中的文件夹? – Noitidart 2016-02-23 11:39:58

+0

哦,我很快就谈到了,我只需要添加到'metadata'对象的父母:['0B5IwavgVGMN9ekR2dEhuaUxkZTA']'其中该字符串是我想要上传到的文件夹的ID。再次感谢@Munawwar! – Noitidart 2016-02-23 11:49:02

+0

我有相同的代码,但我没有使用输入类型=“文件”我已经使用的网址和如何​​上传使用网址上传文件在谷歌驱动器? – 2016-04-14 14:41:57

2

我哗哗有用于驱动gapis V3更好的例子...... 我花了一些时间来弄清楚如何将新的内容上传与

gapi.client.drive.files.create({ "name" : "savefile.txt" }).execute(function(file) { console.log("Created file " + file.name + " id: " + file.id); }); 

但最终创建的现有文件我试图加入的fileid的路径和改变方法的“幸运”组合到PATCH

function uploadFile(id, text)                                       
{ 
    var auth_token = gapi.auth.getToken().access_token; 

    const boundary = '-------314159265358979323846'; 
    const delimiter = "\r\n--" + boundary + "\r\n"; 
    const close_delim = "\r\n--" + boundary + "--"; 

    var metadata = { 
     description : 'savefile for my game', 
     'mimeType': 'application/json' 
    }; 

    var multipartRequestBody = 
    delimiter + 'Content-Type: application/json\r\n\r\n' + 
    JSON.stringify(metadata) + 
    delimiter + 'Content-Type: application/json\r\n\r\n' + 
    text + 
    close_delim; 

    gapi.client.request 
    ({ 
    'path': '/upload/drive/v3/files/'+id, 
    'method': 'PATCH', 
    'params': {'fileId': id, 'uploadType': 'multipart'}, 
    'headers': { 'Content-Type': 'multipart/form-data; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, }, 
    'body': multipartRequestBody 
    }).execute(function(file) { console.log("Wrote to file " + file.name + " id: " + file.id); }); 
} 

但我想,现在整个文档点开始道理给我:-)

+0

代码中的“id”是什么? – 2016-09-26 14:26:31

+0

只是一个简短的提示,如果您使用gapi.client.init并指定您的令牌等,则上述示例中的auth_token不是必需的。 – smaudet 2017-09-22 11:16:45

2

Google Drive APIreleased v3在2015年底,并在该版本中,insert()改名字create(),以便更好地反映文件操作。文档也得到了改进:现在有一个special guide devoted to uploads(简单的,多部分的和可恢复的),带有Java,Python,PHP,C#/ .NET,Ruby,JavaScript/Node.js和iOS/Obj-C中的示例代码用于上传常规文件,另一个用于将Google文件导入为Google表格。

只是为了显示简单的是,下面是一个短文件(“简单的上传”),您不需要apiclient.http.MediaFileUpload类替代 Python的解决方案(以样品中的文档)。此片段假设您的授权码在您的服务端点为DRIVE的地方工作,最小授权范围为https://www.googleapis.com/auth/drive.file

# filenames & MIMEtypes 
DST_FILENAME = 'inventory' 
SRC_FILENAME = DST_FILENAME + '.csv' 
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet' 
CSV_MIMETYPE = 'text/csv' 

# Import CSV file to Google Drive as a Google Sheets file 
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE} 
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute() 
if rsp: 
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType'])) 

请注意,如果你正在写一个Android应用程序,有一个单独的Google Drive API for Android有自己的一套文档的。最后,如果您在Google Apps Script上使用JavaScript,则Drive Service native objectDrive Advanced Service仍在使用API​​的v2。

相关问题