Angular gapi将简单文本上传到Google Drive
我试图使用Angular gapi将简单文本上传到Google Drive,angular,google-drive-api,Angular,Google Drive Api,我试图使用gapi将一个简单的文本文件上传到Google Drive in Angular,但我找不到如何实际填充该文件。我设法验证并创建了一个文件,然后我想使用update函数来更新文件的内容,如前所述 这是我的角度代码: 创建文件: createFile() { return gapi.client.drive.files.create({ resource: { name: `test.csv` } }).then(response
gapi
将一个简单的文本文件上传到Google Drive in Angular,但我找不到如何实际填充该文件。我设法验证并创建了一个文件,然后我想使用update
函数来更新文件的内容,如前所述
这是我的角度代码:
创建文件:
createFile() {
return gapi.client.drive.files.create({
resource: {
name: `test.csv`
}
}).then(response => {
console.log("Response", response.result.id);
return response.result.id;
})
}
这将创建文件,我可以在驱动器的根文件夹中看到它。然后,我尝试添加此文件的内容(使用我刚刚创建的文件的文件ID),但从文档中我不清楚如何在update
调用中传递内容
updateFile(fileId) {
return gapi.client.drive.files.update({
fileId: fileId,
body: "this is the content of my file"
}).then(response => {
console.log("Response", response);
})
}
根据文档中给出的示例(上面的链接),我还尝试在create
调用中直接传递内容
尽管这也不起作用。- 您希望通过使用Javascript将内容包括在内,将文本文件上载到Google Drive
- 您已经能够使用Drive API获取并输入Google Drive的价值
- 您的访问令牌可用于将文件上载到Google Drive
gapi.client.drive.files.create似乎仍然无法发送包含内容的请求。而且,当我现在使用gapi
测试更新方法时,我认为gapi.client.drive.files.update
也无法发送包含内容的请求
因此,在这种情况下,需要使用变通方法。在此解决方法中,使用了fetch
。使用fetch
时,可以轻松创建multipart/form data
请求
模式1:
在这种模式中,文本文件通过使用fetch
的create方法包含内容上传到googledrive
示例脚本:
模式2:
在该模式中,文本文件由gapi.client.drive.files.create
创建,创建的文本文件通过fetch
驱动API的更新方法更新
示例脚本:
参考资料:
感谢您详细而清晰的回答!我选择了选项一,它成功了fine@vdvaxel谢谢你的回复。我很高兴你的问题解决了。
createFile() {
return gapi.client.drive.files.create({
resource: {
name: `test.csv`
},
media: {
body: "this is the content of my file"
}
}).then(response => {
console.log("Response", response.result.id);
})
}
const content = 'this is the content of my file';
const metadata = {name: 'test.txt', mimeType: 'text/plain'};
let form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', new Blob([content], {type: 'text/plain'}));
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST',
headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
body: form
})
.then(res => res.json())
.then(val => console.log(val));
gapi.client.drive.files.create({resource: {name: 'test.txt'}})
.then(response => {
const fileId = response.result.id;
const content = 'this is the content of my file';
const metadata = {name: 'test.txt', mimeType: 'text/plain'};
let form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', new Blob([content], {type: 'text/plain'}));
fetch('https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=multipart', {
method: 'PATCH',
headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
body: form
})
.then(res => res.json())
.then(val => console.log(val));
});