【发布时间】:2013-11-17 20:00:04
【问题描述】:
我正在尝试使用 javascript 将存储在 Google Drive 上的文件(例如 .txt 或 .java 文件)的内容设置为特定的字符串。
我知道更新存储在 Google Drive 上的文件的正确方法是
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);
}
}
但这在将内容设置为特定字符串时不起作用。
【问题讨论】:
-
粘贴http请求和响应
-
我认为您的 close_delim 缺少 \r\n 我在最后做了类似的事情。字符串页脚 = "\r\n--" + 边界 + "--\r\n";
-
我直接从Google Drive SDK website 复制了这个。请求是
PUT https://www.googleapis.com/upload/drive/v2/files/{fileId} -
我可以读取 base 64 中的字符串并将其用作变量“base64data”吗?例如
function utf8_to_b64( str ) { return window.btoa(unescape(encodeURIComponent( str ))); }
标签: javascript google-api google-drive-api