如何将图片从网址上传到Google云端硬盘?

时间:2015-11-21 11:48:06

标签: javascript iframe google-drive-api

我正在尝试将图片从网址上传到Google云端硬盘。来自Google云端硬盘的JavaScript Quickstar t在我的网络应用中完美运行。但现在我想将此图片上传到Google云端硬盘。我在Google的文档中搜索过,发现了一篇文章Files: Insert。但在本文中,您只获得了一个文件对象示例。

是否有人知道如何将图片从网址上传到Google云端硬盘?

这就是我所拥有的:

<html> <head>
    <script type="text/javascript">     
        var CLIENT_ID = <CLIENT_ID>;

        var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

        /**
         * Check if current user has authorized this application.
         */
        function checkAuth() {
            gapi.auth.authorize(
                    {
                        'client_id': CLIENT_ID,
                        'scope': SCOPES.join(' '),
                        'immediate': true
                    }, handleAuthResult);
        }

        /**
         * Handle response from authorization server.
         *
         * @param {Object} authResult Authorization result.
         */
        function handleAuthResult(authResult) {
            var authorizeDiv = document.getElementById('authorize-div');
            if (authResult && !authResult.error) {
                // Hide auth UI, then load client library.
                authorizeDiv.style.display = 'none';
                loadDriveApi();
            } else {
                // Show auth UI, allowing the user to initiate authorization by
                // clicking authorize button.
                authorizeDiv.style.display = 'inline';
            }
        }

        /**
         * Initiate auth flow in response to user clicking authorize button.
         *
         * @param {Event} event Button click event.
         */
        function handleAuthClick(event) {
            gapi.auth.authorize(
                    {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
                    handleAuthResult);
            return false;
        }

        /**
         * Load Drive API client library.
         */
        function loadDriveApi() {
            gapi.client.load('drive', 'v2', insertFile(callback));
        }


         function callback(){
            console.log("It works.");
         }

        /**
         * 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(callback) {
        const boundary = '-------314159265358979323846';
        const delimiter = "\r\n--" + boundary + "\r\n";
        const close_delim = "\r\n--" + boundary + "--";

        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function() {
            var reader  = new FileReader();
            reader.onloadend = function () {
             var  fileData =reader.result;
                var contentType = "image/jpg";
                var metadata = {
                    'title': "cat.jpg",
                    'mimeType': contentType
                };

                var base64Data = btoa(fileData);
                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);
                console.log(fileData);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', "https://scontent.cdninstagram.com/hphotos-xpt1/t51.2885-15/e15/11324950_950675781667048_1239101466_n.jpg");
        xhr.send();

        /**
         * Append a pre element to the body containing the given message
         * as its text node.
         *
         * @param {string} message Text to be placed in pre element.
         */
        function appendPre(message) {
            var pre = document.getElementById('output');
            var textContent = document.createTextNode(message + '\n');
            pre.appendChild(textContent);
        }

    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script> </head> <body> <div id="authorize-div" style="display: none">
    <span>Authorize access to Drive API</span>
    <!--Button for the user to click to initiate auth sequence -->
    <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
    </button> </div> <pre id="output"></pre> </body> </html>

1 个答案:

答案 0 :(得分:0)

花了一些时间才弄明白,但这对我有用。我知道2年后有人会在寻找这个。在您与Google云端硬盘的授权连接后使用此代码。

var image_location = 'https://your_url_location.image.jpg';

var request22 = new XMLHttpRequest();
request22.open('GET', image_location, true);
request22.responseType = 'blob';
request22.onload = function() {
    var fileData = request22.response;


    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    var reader = new FileReader();
    reader.readAsDataURL(fileData);
    reader.onload =  function(e){
        var contentType = fileData.type || 'application/octet-stream';
        var metadata = {
            'name': fileData.fileName,
            'mimeType': contentType
        };
        var data = reader.result;

        var multipartRequestBody =
            delimiter +  'Content-Type: application/json\r\n\r\n' +
            JSON.stringify(metadata) +
            delimiter +
            'Content-Type: ' + contentType + '\r\n';

        //Transfer images as base64 string.
        if (contentType.indexOf('image/') === 0) {
            var pos = data.indexOf('base64,');
            multipartRequestBody += 'Content-Transfer-Encoding: base64\r\n' + '\r\n' +
                data.slice(pos < 0 ? 0 : (pos + 'base64,'.length));
        } else {
            multipartRequestBody +=  + '\r\n' + data;
        }
        multipartRequestBody += close_delim;


        var request = gapi.client.request({
            'path': '/upload/drive/v3/files',
            'method': 'POST',
            'params': {'uploadType': 'multipart'},
            'headers': {
              'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody
        });

        request.execute(function(file){
            if(file.id){
                // send id to STM and mark uploaded
                alert("request execute: "+JSON.stringify(file));
            }
        });

    };
};
request22.send();