在 Android 上,我正在尝试使用 Google Drive API 上传 Cordova/Phonegap getPicture() 的输出:插入文件。有没有办法使用 FILE_URI 而不是 DATA_URL (base64) 来做到这一点?
我首先尝试了 Camera.DestinationType.DATA_URL,但它没有返回应有的 Base64 数据,它只是返回了与 FILE_URI 相同的内容。所以现在我想弄清楚如何将 FILE_URI 传递给 Google Drive Insert File(需要 Base64)。有没有办法将 FILE_URI 转换为 Base64?
科尔多瓦代码:
navigator.camera.getPicture(onSuccess, onFail,
{ quality: 50, destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
// need to do something like this:
var fileData = ConvertToBase64(imageURI);
insertFile(fileData);
}
谷歌云端硬盘代码:
/**
* Insert new file.
*
* @param {File} fileData File object to read data from.
* @param {Function} callback Function to call when the request is complete.
*/
function insertFile(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/octet-stream';
var metadata = {
'title': fileData.fileName,
'mimeType': contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
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',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
}