簡體   English   中英

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

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

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

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

我意識到這有點舊 - 但現在看起來你可以在phoneGap中使用FileReader

我沒有測試過這還,但這樣的事情也應該工作,沒有畫布黑客。

[編輯 - 測試並修改了以下代碼。 適合我: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);

是的,你可以....

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

    }

感謝Arun指出我正確的方向。 我最終使用了這個基於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM