简体   繁体   English

如何使用Google Drive API上传FILE_URI:插入文件

[英]How to upload FILE_URI using Google Drive API: Insert File

On Android, I'm trying to upload the output from Cordova/Phonegap getPicture() using Google Drive API: Insert File. 在Android上,我正在尝试使用Google Drive API上传Cordova / Phonegap getPicture()的输出:插入文件。 Is there a way to do this using the FILE_URI instead of DATA_URL (base64)? 有没有办法使用FILE_URI而不是DATA_URL(base64)?

I tried Camera.DestinationType.DATA_URL first, but it didn't return Base64 data like it was supposed to, it just returned the same thing as FILE_URI. 我首先尝试了Camera.DestinationType.DATA_URL,但它没有像它应该的那样返回Base64数据,它只返回与FILE_URI相同的东西。 So now I'm trying to figure out how to pass FILE_URI to Google Drive Insert File (which takes Base64). 所以现在我想弄清楚如何将FILE_URI传递给Google Drive Insert File(需要Base64)。 Is there a way to convert FILE_URI to Base64? 有没有办法将FILE_URI转换为Base64?

Cordova code: 科尔多瓦代码:

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);
}

Google Drive code: Google云端硬盘代码:

/**
 * 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);
  }
}

I realize this is a bit old - but it now looks like you can use a FileReader in phoneGap. 我意识到这有点旧 - 但现在看起来你可以在phoneGap中使用FileReader

I haven't tested this yet, but something like this should also work, without the canvas hack. 我没有测试过这还,但这样的事情也应该工作,没有画布黑客。

[EDIT - tested and revised the code below. [编辑 - 测试并修改了以下代码。 works for me :D ] 适合我:D]

var cfn = function(x) { console.log(x) };
var cameraOps = { quality: 50, destinationType: Camera.DestinationType.FILE_URI };
navigator.camera.getPicture(function(imagePath) {
    window.resolveLocalFileSystemURL(imagePath, function(fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function(evt) {
                console.log("read success!!!");
                console.log(evt.target.result);
            };
            reader.readAsDataURL(file);
        }, cfn);
    }, cfn);
}, cfn);

Yes you can.... 是的,你可以....

Specify Destination Type as FILE_URI itself and in imagedata you will be getting the images file uri place it in a image tag and then place it inside HTML5 canvas and canvas has one method called toDataURL where you will be able to get the base64 of the corresponding image. Destination Type指定为FILE_URI本身,在imagedata中,您将获取图像文件,将其放置在图像标记中,然后将其放在HTML5 canvas ,画布有一个名为toDataURL的方法,您可以在其中获取相应图像的base64 。

function onSuccess(imageData)
     {

                var $img = $('<img/>');
                $img.attr('src', imageData);
                $img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
                $img.bind('load', function() 
                {
                    var canvas = document.createElement("canvas");
                    canvas.width = $img.width();
                    canvas.height = $img.height();
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage($img[0], 0, 0);
                    var dataUri = canvas.toDataURL('image/png');

                });
                $img.bind('error', function() 
                {
                    console.log('Couldnt convert photo to data URI');
                });

    }

Thanks to Arun for pointing me in the right direction. 感谢Arun指出我正确的方向。 I ended up using this javascript function, which was based off http://jsfiddle.net/jasdeepkhalsa/L5HmW/ 我最终使用了这个基于http://jsfiddle.net/jasdeepkhalsa/L5HmW/的 javascript函数

function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
    var canvas = document.createElement("canvas");
    canvas.width = imgElem.clientWidth;
    canvas.height = imgElem.clientHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgElem, 0, 0);
    var dataURL = canvas.toDataURL("image/jpeg");
    dataURL = dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
    return dataURL;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ionic 4 (android) 从图库 (FILE_URI) 获取图像 (OBJECT FILE) 并通过 API 上传 - ionic 4 (android) get image (OBJECT FILE) from gallery (FILE_URI) and upload via API 使用Google Drive Api上传文件 - Upload file using Google Drive Api 如何使用 Google Drive API 从 android 将加密的图像文件上传到 Google Drive - How to upload encrypted image file on google drive from android using Google Drive API 如何将文件上传到Google云端硬盘 - How to upload a file to Google Drive 如何使用Google Drive Android API删除Google Drive上的文件 - How to delete a file on google drive using Google Drive Android API 无法使用 REST API 在谷歌驱动器的特定文件夹中上传文件 - Unable to upload file in specific folder in google drive using REST API 在 Android Studio 中使用 Google Drive API 从驱动器下载文件以上传到另一个驱动器 - Download file from drive to upload into another drive using Google Drive API in Android Studio 如何上传带有链接的文件到Google Drive REST API v2 - How to upload a file with a link to Google Drive REST API v2 Google Drive Android API如何将音频文件上传到我的驱动器? 如何同步驱动器文件? - Google Drive Android API how to upload a audio file to my drive ? How to sync drive files? 如何使用最新的 Google Sign-In 和 Drive REST api 上传 SQLite 数据库文件? - How to upload a SQLite database file using the latest Google Sign-In and Drive REST api?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM