2012-04-25 141 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。

相關問題