Allow Multiple Files Upload on Google Apps Script

被刻印的时光 ゝ 提交于 2019-12-01 12:51:59

You can use Google Drive Picker, which has no upload limit on file sizes. Before you use this code, you need to do some configuration.

  1. In the script editor, select Resources > Developers Console Project.Enable Drive Api. After that click on Google API console. It will redirect to your API Manager page.
  2. Then, click on Enable API.
  3. In the filter box, type "picker", then select "Google Picker API"
  4. On the next screen, click Enable API.
  5. In the console's left navigation, click Credentials.
  6. Then click on "Create credentials" then API key.
  7. Once the API Key is created, edit it by clicking on the pencil icon.
  8. Then change the "Key restriction" option to Under "Accept requests from these HTTP referrers (websites) ", Add these URLs as referrers and then click Create:
    *.google.com
    *.googleusercontent.com

  9. Copy the API Key and paste it in the code below. var DEVELOPER_KEY="key" Also create folder in google drive where all the attachments will be uploaded.
  10. Once the drive folder is created, add the respective id of the folder to var uploadview = new google.picker.DocsUploadView().setParent('<<Drive API>>');

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <style>
      #attachmentTable{ 
      background: white;
      }
      tr th,tr td{
      text-align:center;
      }
     </style>
    </head>
    <body style='font-family: cursive;'>
      <div>
        <center><button onclick='getOAuthToken()' style="margin-top:50px;outline:0;" class="btn btn-success">Upload File(s)</button></center>
      <div class='table-responsive' style="display:none;" id="attachmentTableDiv">
      <table id="attachmentTable" class="table table-bordered" style="width:900px;margin:20px auto;float:none;">
          <thead>
            <tr style="background:#f1f1f1;">
              <th>Title</th>
              <th>ID</th>
              <th>URL</th>
              <th>Date Created</th>
              <th>Download</th>
            </tr>
          </thead>
          <tbody>
    
          </tbody>
        </table>
        </div>
      </div>
        <script>
        var DEVELOPER_KEY = '<<YOUR API KEY>>'; 
        var pickerApiLoaded = false;
    
        /**
         * Loads the Google Picker API.
         */
        function onApiLoad() {
          gapi.load('picker', {'callback': function() {
            pickerApiLoaded = true;
          }});
         }
    
    
        function getOAuthToken() {
          google.script.run.withSuccessHandler(createPicker).getOAuthToken();
        }
    
    
        function createPicker(token) {
          if (pickerApiLoaded && token) {
          // var all         = new google.picker.DocsView(google.picker.ViewId.DOCS); //To upload from Google Drive
           var uploadview  = new google.picker.DocsUploadView().setParent('<<Drive API>>');  //To upload from local machine..Add you google drive folder
           var picker = new google.picker.PickerBuilder()
                .addView(uploadview)
                //.addView(all)
                .hideTitleBar()
                //.setLocale('nl') //--Regional language settings
                //.enableFeature(google.picker.Feature.NAV_HIDDEN)
                .setOAuthToken(token)
                .setSize(536, 350)
                .setDeveloperKey(DEVELOPER_KEY)
                .setCallback(pickerCallback)
                .setOrigin(google.script.host.origin)
                .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                .build();
            picker.setVisible(true);
          } else {
            showError('Unable to load the file picker.');
          }
        }
    
        /**
         * A callback function that extracts the chosen document's metadata from the response object. 
         */
        function pickerCallback(data) {
          var action = data[google.picker.Response.ACTION];
          if (action == google.picker.Action.PICKED) {
            for(var i in data[google.picker.Response.DOCUMENTS]){
            var doc = data[google.picker.Response.DOCUMENTS][i];
            var id = doc[google.picker.Document.ID];
            var url = doc[google.picker.Document.URL];
            var title = doc[google.picker.Document.NAME];
            var dateCreated = doc[google.picker.Document.LAST_EDITED_UTC];
            var date = new Date(dateCreated);
            date=date.toLocaleString();
            $('#attachmentTable tbody').append("<tr><td>"+title+"</td><td>"+id+"</td><td><a href='"+url+"' target='_blank'>Link</a></td><td>"+date+"</td><td><a href='https://drive.google.com/drive/uc?export=download&id="+id+"'><i class='glyphicon glyphicon-download-alt'></i></a></td></tr>");
            $('#attachmentTableDiv').show();
          }
        }
    }
      </script>
      <script type="text/javascript" src="https://www.google.com/jsapi"></script>
      <script>google.load("picker", "1", {callback:function(){pickerApiLoaded =!0}});</script>
    </body>
    </html>
    

    code.gs

    /*   
    Fetch the oAuthToken 
    */
    function getOAuthToken() {
      DriveApp.getRootFolder();
      Logger.log(ScriptApp.getOAuthToken())
      return ScriptApp.getOAuthToken();
    
    }
    
    
    function doGet(){
    return HtmlService.createTemplateFromFile('drivePicker') 
              .evaluate()
              .setTitle('Google Drive Picker')
              .setSandboxMode(HtmlService.SandboxMode.IFRAME);  
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!