简体   繁体   English

将PDF文件上传到Google云端硬盘

[英]Upload PDF file to Google Drive

I am trying to upload the file below to my Google Drive with Javascript, and using the Google Developer's example. 我正在尝试使用Java 开发者的示例将以下文件上传到使用Javascript的Google云端硬盘。 The file is created on the fly by a user selection process, then auto-downloaded to default dir (downloads). 该文件是由用户选择过程动态创建的,然后自动下载到默认目录(下载)。 Is there a way to place the file on Google Drive at the same time? 是否可以同时将文件放置在Google云端硬盘上? I am using jsPDF and have tried a few things like below but not successful. 我正在使用jsPDF,并尝试了以下类似操作,但未成功。

E:\Downloads\MyFile.pdf

I am bypassing the file picker as I know which file to upload. 我绕过文件选择器,因为我知道要上传哪个文件。 I have modified the Google example to pass the code the file name but it is failing. 我已经修改了Google示例,以将文件名传递给代码,但是失败了。

I think I need to create a Blob of the file on my HDD to then pass to the Google API but I have tried a few combinations without success. 我想我需要在HDD上创建文件的Blob,然后传递给Google API,但我尝试了几种组合,但均未成功。 Any help is appreciated. 任何帮助表示赞赏。

<html>
  <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <script type="text/javascript">
      var CLIENT_ID = 'my-client-id';
      var SCOPES = 'https://www.googleapis.com/auth/drive';
      var FOLDER_ID = 'my-drive-folder-id';

      /**
       * Called when the client library is loaded to start the auth flow.
       */
      function handleClientLoad() {
        window.setTimeout(checkAuth, 1);
      }

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

      /**
       * Called when authorization server replies.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        if (authResult && !authResult.error) {
            var MyFile = "E:\PAPA\Downloads\test.pdf";
            insertFile(MyFile);
        }
      }

      /**
       * Start the file upload.
       *
       * @param {Object} evt Arguments from the file selector.
       */
      function uploadFile(evt) {
        gapi.client.load('drive', 'v2', function() {
          var file = evt.target.files[0];
          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,
            'parents': [{"id":FOLDER_ID}]
          };

          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);
        }
      }
    </script>
    <script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
  </head>
  <body>
    <!--Add a file picker for the user to start the upload process -->
    <input type="file" id="filePicker" style="display: none" />
    <input type="button" id="authorizeButton" style="display: none" value="Authorize" />
  </body>
</html>

I am bypassing the file picker as I know which file to upload. 我绕过文件选择器,因为我知道要上传哪个文件。 I have modified the Google example to pass the code the file name but it is failing. 我已经修改了Google示例,以将文件名传递给代码,但是失败了。

This is the problem. 这就是问题。

A string containing a file name is not a file. 包含文件名的字符串不是文件。

Browsers do not provide a means for web sites to read files from visitors' drives based on the file name (it would be a huge security hole). 浏览器没有为网站提供一种基于文件名从访问者的驱动器中读取文件的方法(这将是一个巨大的安全漏洞)。

You could integrate with the Save to Drive button: https://developers.google.com/drive/web/savetodrive 您可以与“保存到驱动器”按钮集成: https : //developers.google.com/drive/web/savetodrive

Then you don't have to worry about the extra redirect via their local downloads folder. 然后,您不必担心通过其本地下载文件夹进行的额外重定向。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM