str*_*hod 12 javascript google-drive-api
我想使用Google Drive API V3(javascript)更新Google文档的内容:
https://developers.google.com/drive/v3/reference/files/update
我能够更新文件元数据(例如名称),但文档不包含实际文件内容的补丁语义.有没有办法JSON.stringify()在gapi.client.drive.files.update请求中传递值作为参数:
var request = gapi.client.drive.files.update({
'fileId': fileId,
'name' : 'Updated File Name',
'uploadType': 'media',
'mimeType' : 'application/vnd.google-apps.document'
});
var fulfilledCallback = function(fulfilled) {
console.log("Update fulfilled!", fulfilled);
};
var rejectedCallback = function(rejected) {
console.log("Update rejected!", rejected);
};
request.then(fulfilledCallback, rejectedCallback)
Run Code Online (Sandbox Code Playgroud)
Eri*_*eda 13
有两个问题:
您可以通过编写自己的基于XHR的上传功能来解决问题#1.以下代码应适用于大多数现代Web浏览器:
function updateFileContent(fileId, contentBlob, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState != XMLHttpRequest.DONE) {
return;
}
callback(xhr.response);
};
xhr.open('PATCH', 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media');
xhr.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
xhr.send(contentBlob);
}
Run Code Online (Sandbox Code Playgroud)
要解决问题#2,您可以向云端硬盘发送Google文档可以导入的文件类型,例如.txt,.docx等.以下代码使用上述功能使用纯文本更新Google文档的内容:
function run() {
var docId = '...';
var content = 'Hello World';
var contentBlob = new Blob([content], {
'type': 'text/plain'
});
updateFileContent(fileId, contentBlob, function(response) {
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我使用javascript v3 api构建gDriveSync.js库以与google驱动器同步https://github.com/vitogit/gDriveSync.js
您可以查看我所做的源代码(https://github.com/vitogit/gDriveSync.js/blob/master/lib/drive.service.js),基本上是一个两步过程,首先创建文件并然后你更新它.
this.saveFile = function(file, done) {
function addContent(fileId) {
return gapi.client.request({
path: '/upload/drive/v3/files/' + fileId,
method: 'PATCH',
params: {
uploadType: 'media'
},
body: file.content
})
}
var metadata = {
mimeType: 'application/vnd.google-apps.document',
name: file.name,
fields: 'id'
}
if (file.parents) {
metadata.parents = file.parents;
}
if (file.id) { //just update
addContent(file.id).then(function(resp) {
console.log('File just updated', resp.result);
done(resp.result);
})
} else { //create and update
gapi.client.drive.files.create({
resource: metadata
}).then(function(resp) {
addContent(resp.result.id).then(function(resp) {
console.log('created and added content', resp.result);
done(resp.result);
})
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3929 次 |
| 最近记录: |