使用javascript更新google drive上的文件内容
基于@Nvico great,我能够将文件上传到google drive,问题是答案上的代码每次都会创建一个新文件,有没有一种方法可以让已经创建的文件id直接(使用api)更新其内容而不创建新文件使用javascript更新google drive上的文件内容,javascript,google-drive-api,Javascript,Google Drive Api,基于@Nvico great,我能够将文件上传到google drive,问题是答案上的代码每次都会创建一个新文件,有没有一种方法可以让已经创建的文件id直接(使用api)更新其内容而不创建新文件 目前,我的解决方案是每次更新文件时使用api以删除旧文件,然后使用@Nvico代码创建新文件,而不是使用drive.files.insert端点,您可以使用几乎相同的代码向drive.files.update端点发送更新请求: /** * Update existing file. * * @p
目前,我的解决方案是每次更新文件时使用api以删除旧文件,然后使用@Nvico代码创建新文件,而不是使用drive.files.insert端点,您可以使用几乎相同的代码向drive.files.update端点发送更新请求:
/**
* Update existing file.
*
* @param {String} fileId ID of the file to update.
* @param {Object} fileMetadata existing Drive file's metadata.
* @param {File} fileData File object to read data from.
* @param {Function} callback Callback function to call when the request is complete.
*/
function updateFile(fileId, fileMetadata, fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
var contentType = fileData.type || 'application/octect-stream';
// Updating the metadata is optional and you can instead use the value from drive.files.get.
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(fileMetadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + fileId,
'method': 'PUT',
'params': {'uploadType': 'multipart', 'alt': 'json'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
}
主要区别在于请求URL和方法:
PUT /upload/drive/v2/files/<FILE_ID>
PUT/upload/drive/v2/文件/
谢谢,这是可行的,我自己尝试过只在原始代码中更改端点,但没有成功,可能是因为alt:json?我不知道可能是url中的输入错误。。无论如何谢谢:)您可能忘记将方法从POST
更改为PUT
。alt=json
query参数在发送文本内容数据时非常有用,可以让API知道json文档是元数据,而另一部分是内容。@Alain-您能帮助传递什么文件数据吗?试图传递字符串不起作用。它需要哪个对象以及如何获得它?