Download file right after picked file from google picker

☆樱花仙子☆ 提交于 2019-12-06 04:36:04

You need to get the download URL of the file using its file id. Once done you can call that URL using AJAX to get the file data. Optionally, you can send the file bytes as blob in form data to server side.

var googleSelectedFiles = new Array();

if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {

    var docs = data[google.picker.Response.DOCUMENTS];
    docs.forEach(function (file) {

        var downloadUrl;

        gapi.client.request({
            'path': '/drive/v2/files/' + file.id,
            'method': 'GET',
            callback: function (responsejs, responsetxt) {

                downloadUrl = responsejs.downloadUrl;

                var gDoxBlob = null;
                var xhr = new XMLHttpRequest();
                xhr.open("GET", downloadUrl); //file.url

                var accessToken = gapi.auth.getToken().access_token;
                xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);

                xhr.responseType = "blob";
                xhr.onload = function () {

                    gDoxBlob = xhr.response;
                    googleSelectedFiles.push({ bytes: gDoxBlob, name: file.name });
                }
                xhr.send();

            }
        });

    });

}

I hope you're able to look file picker and you now want to download selected file, the following code is able to do so:

First modify your createPicker callback:

function pickerCallback(data) {
        var url = 'nothing';
        if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
            var fileId = data.docs[0].id;
            getDownloadurl(fileId);    //this is the custom function

        }       
    }

Then Implement getDownloadUrl:

function getDownloadUrl(fileId) {
            /*Before executing following client request you must include
                <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
            google client library*/

            var request =
                gapi.client.request({
                    'path': '/drive/v2/files/' + fileId,
                    'params': { 'maxResults': '1000' },
                    callback: function (responsejs, responsetxt) {
                            var fileDownloadUrl = responsejs.downloadUrl; //using this downloadUrl you will be able to download Drive File Successfully
                    }
                });
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!