2013-07-01 187 views
0

我想让我的网站用户能够上传他们创建的存储在我的服务器上的文件,以便上传到那里的谷歌云端硬盘帐户。使用javascript将服务器上的文件上传到谷歌驱动器

我尝试过验证并将此accesstoken传递给.net,但无法让该流程正常工作。 Using existing access token for google drive request in .net

所以,现在我需要帮助,只用JavaScript做到这一点。我如何在后台下载文件,然后将它传递给api?

如果可能,我想避免使用保存到驱动器按钮。

这里是我当前的代码:

gapi.client.load('drive', 'v2', function() { 
     //How do i download a file and then pass it on. 
     var file = 
     insertFile(file); 
    }); 


    /** 
    * 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.name, 
     '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); 
    } 
    } 

回答

0

有使用XMLHttpRequest的下载从GET请求文件到二进制字符串的例子很多。例如,像this one。您可以将读取文件的部分替换为二进制字符串reader.readAsBinaryString(fileData);到此代码。

+0

传说!指引我到完美的联系。在问题中使用示例时遇到问题,但只要我实际阅读帖子并实现了它的工作答案就像一个享受! 非常感谢你!!!!!!!! –

相关问题