简体   繁体   English

如何将图像从 url 上传到 Google Drive?

[英]How to upload an image from an url to Google Drive?

I am trying to upload an image from an url to Google Drive.我正在尝试将图像从 url 上传到 Google Drive。 The JavaScript Quickstar t from Google Drive work perfectly in my web app.来自 Google Drive 的JavaScript Quickstart在我的网络应用程序中完美运行。 But now I want to upload this image to the Google Drive.但现在我想将此图片上传到 Google Drive。 I have searched in Google's documentation and I found an article Files: Insert .我在谷歌的文档中搜索过,我找到了一篇文章Files: Insert But in this article you get only an example with a file object.但在本文中,您只会得到一个带有文件对象的示例。

Do some one know how to upload an image from an url to Google Drive?有人知道如何将图像从网址上传到 Google 云端硬盘吗?

This is what I have:这就是我所拥有的:

<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>

Took me some time to figure out, but this worked for me.我花了一些时间来弄清楚,但这对我有用。 I know that 2 years later someone will be looking for this.我知道 2 年后有人会找这个。 use this code after your authorized connection to Google Drive.在您授权连接到 Google Drive 后使用此代码。

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

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

相关问题 通过 Google Drive API Javascript 将图像从 URL 上传到 Google Drive - Upload image from URL to Google Drive through Google Drive API Javascript 如何从 Node 中的图像 url 将图像上传到 Google Cloud Storage? - How to upload an image to Google Cloud Storage from an image url in Node? "使用谷歌脚本将从 webapp 获取的输入图像上传到谷歌驱动器" - Upload an input image taken from webapp into google drive with google script 如何从谷歌选择器上传获取图像URL - How to get image URL from google picker upload 如何将文件上传到 url 中的谷歌驱动器? - How can I upload files to google drive that are in a url? 从 Google 云端硬盘 API 中检索原始文件 URL - Retrieving a raw file URL from the Google Drive API 无法在 js 中识别 Google Drive 上传的图片 - Cannot recognize image upload at Google Drive in js 如何从 NodeJS 上传图片到 google drive API - How to upload images to google drive from NodeJS API 如何发出 HTTP 请求以将文件从 reactjs 上传到谷歌驱动器? - How to make HTTP request to upload file from reactjs to google drive? 如何使用javascript将文件从Google驱动器上传到服务器 - How to upload file from google drive to server using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM