我试图使用javascript将存储在Google Drive上的文件(例如.txt或.java文件)的内容设置为特定的String。
我知道更新存储在Google Drive上的文件的正确方法是
function updateFile(fileId, fileMetadata, fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "rn--" + boundary + "rn";
const close_delim = "rn--" + 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/jsonrnrn' +
JSON.stringify(fileMetadata) +
delimiter +
'Content-Type: ' + contentType + 'rn' +
'Content-Transfer-Encoding: base64rn' +
'rn' +
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);
}
}
但这在将内容设置为特定字符串时没有起到作用。
没关系。我找到了问题的答案。使用我的问题中的方法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^^^^^^
});
}