我正在尝试使用javascript来将存储在Google云端硬盘中的文件内容(例如.txt或.java文件)设置为特定的字符串。
我知道更新存储在Google云端硬盘中的文件的正确方法是
function updateFile(fileId, fileMetadata, fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
//console.log("fileId: "+fileId+" fileData: "+fileData);
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
console.log("reader initialized");
var contentType = fileData.type || 'application/octet-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);
}
}
但这并没有将内容设置为特定的字符串。
答案 0 :(得分:2)
没关系。我找到了问题的答案。使用我的问题中的方法updateFile
:
function save(fileId, content){
var contentArray = new Array(content.length);
for (var i = 0; i < contentArray.length; i++) {
contentArray[i] = content.charCodeAt(i);
}
var byteArray = new Uint8Array(contentArray);
var blob = new Blob([byteArray], {type: 'text/plain'});
var request = gapi.client.drive.files.get({'fileId': fileId});
request.execute(function(resp) {
updateFile(fileId,resp,blob,changesSaved);
// the callback^^^^^^
});
}