問題描述
我想使用 Google Drive API v3 創(chuàng)建一個包含內(nèi)容的文件.我已通過 OAuth 進(jìn)行身份驗證并加載了 Drive API.像下面這樣的語句可以工作(但會生成一個沒有內(nèi)容的文件):
I want to create a file with content using Google Drive API v3. I have authenticated via OAuth and have the Drive API loaded. Statements like the following work (but produce a file without content):
gapi.client.drive.files.create({
"name": "settings",
}).execute();
不幸的是,我不知道如何創(chuàng)建包含內(nèi)容的文件.我找不到使用 Drive API v3 的 JavaScript 示例.我需要傳遞一些特殊的參數(shù)嗎?
Unfortunately I cannot figure out how to create a file that has a content. I cannot find a JavaScript example using Drive API v3. Are there some special parameters that I need to pass?
為簡單起見,假設(shè)我有一個類似 '{"name":"test"}' 的字符串,它是 JSON 格式,應(yīng)該是創(chuàng)建文件的內(nèi)容.
For simplicity, assume that I have a String like '{"name":"test"}' that is in JSON format that should be the content of the created file.
推薦答案
這里是gapi.client.drive
的解決方案,
var parentId = '';//some parentId of a folder under which to create the new folder
var fileMetadata = {
'name' : 'New Folder',
'mimeType' : 'application/vnd.google-apps.folder',
'parents': [parentId]
};
gapi.client.drive.files.create({
resource: fileMetadata,
}).then(function(response) {
switch(response.status){
case 200:
var file = response.result;
console.log('Created Folder Id: ', file.id);
break;
default:
console.log('Error creating the folder, '+response);
break;
}
});
您需要連接/授權(quán)以下范圍
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
可以通過將 mimeType
從 application/vnd.google-apps.folder
更改為一個來創(chuàng)建 google 文件(文檔、表格等)支持的 google mime 類型.但是,目前無法將任何內(nèi)容上傳到創(chuàng)建的文件中.
it is possible to create google files (doc, sheets and so on) by changing the mimeType
from application/vnd.google-apps.folder
to one of the supported google mime types. HOWEVER, as of now it not possible to upload any content into created files.
要上傳文件,請使用 @Geminus 提供的解決方案.請注意,您可以上傳文本文件或 csv 文件并將其內(nèi)容類型分別設(shè)置為 google doc 或 google sheet,google 將嘗試對其進(jìn)行轉(zhuǎn)換.我已經(jīng)為 text -> doc 測試了這個,它可以工作.
To upload files, use the solution provided by @Geminus. Note you can upload a text file or a csv file and set its content type to google doc or google sheets respectively, and google will attempt to convert it. I have tested this for text -> doc and it works.
這篇關(guān)于使用 Google Drive Api v3 (javascript) 創(chuàng)建文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!