如何在服务器上下载Google Drive File

时间:2014-12-15 08:43:31

标签: javascript google-drive-api

我已经使用JavaScript从Google驱动器编写了以下代码来下载文件,但我无法在下载完成后打开文件,因为文件格式的错误与我的代码不符,如下所示

 function createPicker() {
    var picker = new FilePicker({
        apiKey: 'myapikey',
        clientId: 'myclientID',
        buttonEl: document.getElementById('ancggdgdgdd'),
        onSelect: function (file) {
            downloadFile(file);
        }
    });
}

并将文件代码的内容读作:

function downloadFile(doc) {
    var myToken = gapi.auth.getToken();
    var contentType = "text/plain;charset=utf-8";
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", doc.downloadUrl, false);
    rawFile.setRequestHeader('Content-type', contentType)

    rawFile.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {

                sendFile(rawFile.responseText);//here I am sending httpcontext
            }
        }
    }
    //rawFile.responseType = "arraybuffer";
    rawFile.send(null);
}

1 个答案:

答案 0 :(得分:0)

尝试使用此功能下载文件:

/**
* Download a file's content.
*
* @param {File} file Drive File instance.
* @param {Function} callback Function to call when the request is complete.
*/
function downloadFile(file, callback) {
  if (file.downloadUrl) {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.downloadUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}

您可以在以下链接中找到更多信息:https://developers.google.com/drive/web/manage-downloads