使用 Google Drive Api v3 (javascript) 创建文件
我想使用 Google Drive API v3 创建一个包含内容的文件.我已通过 OAuth 进行身份验证并加载了 Drive API.像下面这样的语句可以工作(但会生成一个没有内容的文件):
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();
不幸的是,我不知道如何创建包含内容的文件.我找不到使用 Drive API v3 的 JavaScript 示例.我需要传递一些特殊的参数吗?
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?
为简单起见,假设我有一个类似 '{"name":"test"}' 的字符串,它是 JSON 格式,应该是创建文件的内容.
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;
}
});
您需要连接/授权以下范围
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
可以通过将 mimeType
从 application/vnd.google-apps.folder
更改为一个来创建 google 文件(文档、表格等)支持的 google mime 类型.但是,目前无法将任何内容上传到创建的文件中.
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 文件并将其内容类型分别设置为 google doc 或 google sheet,google 将尝试对其进行转换.我已经为 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.
相关文章