title: Upload file to my google drive with Google Apps Script (NO FORM IN GOOGLE)
body: <p>so basically the task is quite simple, but I didn't find any workable solution for my problem. I have a huge upload script on my website (at the moment localhost), but lets reduce all the complexity to the only neccessary.</p>
  <p><strong>So I just want to upload a single file to Google Drive with Google App Script and receive the URL of it to save it in a var, to work with that information on a later point in my function.</strong></p>
  <p>Now the problem is I already have the form on my website, I dont want the form inside script.google.com as extra html, I want to transfer my user input to Google App Script, then upload it to google drive and return the url back to my website where I can save it into a var.</p>
  <p>My problem now is, I cant put all the stuff together.</p>
  <p><strong>This is the form on my website (simplified):</strong></p>
  <pre><code>&lt;form name=&quot;myForm&quot; method=&quot;post&quot;&gt;
              &lt;!-- &lt;form name=&quot;first-form&quot;&gt; --&gt;
  
    &lt;input type=&quot;text&quot; placeholder=&quot;Name&quot; id=&quot;myName&quot;&gt;
    &lt;input type=&quot;file&quot; name=&quot;myFile&quot; id=&quot;myFile&quot;&gt;
    &lt;button onclick=&quot;UploadFile()&quot; type=&quot;submit&quot;&gt;submit&lt;/button&gt;
  
  &lt;/form&gt;
  </code></pre>
  <p>So how can I upload my informations inside google drive and get back a result? How can I push the data in Google App Script without using iFrame or anything else?</p>
  <p>THANK YOU!</p>
  <p>**** Working example if html is in scripts.google.com ****</p>
  <p>gs</p>
  <pre><code>function doGet(e) {
    return HtmlService.createHtmlOutputFromFile('forms.html').setTitle(&quot;Google File Upload by CTRLQ.org&quot;);
  }
  
  
  function uploadFileToGoogleDrive(data, file, name, email) {
    
    try {
      
      var dropbox = &quot;Received Files&quot;;
      var folder, folders = DriveApp.getFoldersByName(dropbox);
      
      if (folders.hasNext()) {
        folder = folders.next();
      } else {
        folder = DriveApp.createFolder(dropbox);
      }
      
      /* Credit: www.labnol.org/awesome */
      
      var contentType = data.substring(5,data.indexOf(';')),
          bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
          blob = Utilities.newBlob(bytes, contentType, file),
          file = folder.createFolder([name, email].join(&quot; &quot;)).createFile(blob);
      
      return &quot;OK&quot;;
      
    } catch (f) {
      return f.toString();
    }
    
  }
  </code></pre>
  <p>html in apps.googlescript</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;base target=&quot;_blank&quot;&gt;
      &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
      &lt;title&gt;Google File Upload by CTRLQ.org&lt;/title&gt;
      &lt;link href=&quot;https://fonts.googleapis.com/icon?family=Material+Icons&quot; rel=&quot;stylesheet&quot;&gt;
      &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css&quot;&gt;
      &lt;style&gt;
        .disclaimer{width: 480px; color:#646464;margin:20px auto;padding:0 16px;text-align:center;font:400 12px Roboto,Helvetica,Arial,sans-serif}.disclaimer a{color:#009688}#credit{display:none}
      &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
  
      &lt;!-- Written by Amit Agarwal amit@labnol.org --&gt; 
  
      &lt;form class=&quot;main&quot; id=&quot;form&quot; novalidate=&quot;novalidate&quot; style=&quot;max-width: 480px;margin: 40px auto;&quot;&gt;
        &lt;div id=&quot;forminner&quot;&gt;
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;col s12&quot;&gt;
              &lt;h5 class=&quot;center-align teal-text&quot;&gt;Upload Files to my Google Drive&lt;/h5&gt;
              &lt;p class=&quot;disclaimer&quot;&gt;This &lt;a href=&quot;http://www.labnol.org/internet/file-upload-google-forms/29170/&quot;&gt;File Upload Form&lt;/a&gt; (&lt;a href=&quot;https://youtu.be/C_YBBupebvE&quot;&gt;tutorial&lt;/a&gt;) is powered by &lt;a href=&quot;https://ctrlq.org/code/19747-google-forms-upload-files&quot; target=&quot;_blank&quot;&gt;Google Scripts&lt;/a&gt;&lt;/p&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;input-field col s12&quot;&gt;
              &lt;input id=&quot;name&quot; type=&quot;text&quot; name=&quot;Name&quot; class=&quot;validate&quot; required=&quot;&quot; aria-required=&quot;true&quot;&gt;
              &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;input-field col s12&quot;&gt;
              &lt;input id=&quot;email&quot; type=&quot;email&quot; name=&quot;Email&quot; class=&quot;validate&quot; required=&quot;&quot; aria-required=&quot;true&quot;&gt;
              &lt;label for=&quot;email&quot;&gt;Email Address&lt;/label&gt;
            &lt;/div&gt;
          &lt;/div&gt;
  
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;file-field input-field col s12&quot;&gt;
              &lt;div class=&quot;btn&quot;&gt;
                &lt;span&gt;File&lt;/span&gt;
                &lt;input id=&quot;files&quot; type=&quot;file&quot;&gt;
              &lt;/div&gt;
              &lt;div class=&quot;file-path-wrapper&quot;&gt;
                &lt;input class=&quot;file-path validate&quot; type=&quot;text&quot; placeholder=&quot;Select a file on your computer&quot;&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
  
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;input-field col s6&quot;&gt;
              &lt;button class=&quot;waves-effect waves-light btn submit-btn&quot; type=&quot;submit&quot; onclick=&quot;submitForm(); return false;&quot;&gt;Submit&lt;/button&gt;
            &lt;/div&gt;   
          &lt;/div&gt;
          &lt;div class=&quot;row&quot;&gt;
            &lt;div class=&quot;input-field col s12&quot; id = &quot;progress&quot;&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;success&quot; style=&quot;display:none&quot;&gt;
          &lt;h5 class=&quot;left-align teal-text&quot;&gt;File Uploaded&lt;/h5&gt;
          &lt;p&gt;Your file has been successfully uploaded.&lt;/p&gt;
          &lt;p&gt;The &lt;a href=&quot;http://www.labnol.org/internet/file-upload-google-forms/29170/&quot;&gt;pro version&lt;/a&gt; (see &lt;a href=&quot;&quot;&gt;demo form&lt;/a&gt;) includes a visual drag-n-drop form builder, CAPTCHAs, the form responses are saved in a Google Spreadsheet and respondents can upload multiple files of any size.&lt;/p&gt;    
          &lt;p class=&quot;center-align&quot;&gt;&lt;a  class=&quot;btn btn-large&quot; href=&quot;https://gum.co/GA14?wanted=true&quot; target=&quot;_blank&quot;&gt;Upgrade to Pro&lt;/a&gt;&lt;/p&gt;
        &lt;/div&gt;
      &lt;/form&gt;
  
      &lt;div class=&quot;fixed-action-btn horizontal&quot; style=&quot;bottom: 45px; right: 24px;&quot;&gt;
        &lt;a class=&quot;btn-floating btn-large red&quot;&gt;
          &lt;i class=&quot;large material-icons&quot;&gt;menu&lt;/i&gt;
        &lt;/a&gt;
        &lt;ul&gt;
          &lt;li&gt;&lt;a class=&quot;btn-floating red&quot;  href=&quot;https://gum.co/GA14&quot; target=&quot;_blank&quot; title=&quot;Buy License - File Upload Form&quot;&gt;&lt;i class=&quot;material-icons&quot;&gt;monetization_on&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a class=&quot;btn-floating blue&quot;  href=&quot;https://youtu.be/C_YBBupebvE&quot; target=&quot;_blank&quot; title=&quot;Video Tutorial&quot;&gt;&lt;i class=&quot;material-icons&quot;&gt;video_library&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a class=&quot;btn-floating green&quot; href=&quot;http://www.labnol.org/internet/file-upload-google-forms/29170/&quot; target=&quot;_blank&quot; title=&quot;How to Create File Upload Forms&quot;&gt;&lt;i class=&quot;material-icons&quot;&gt;help&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
  
      &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js&quot;&gt;&lt;/script&gt;
      &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js&quot;&gt;&lt;/script&gt;
      &lt;script src=&quot;https://gumroad.com/js/gumroad.js&quot;&gt;&lt;/script&gt;
  
      &lt;script&gt;
  
        var file, 
            reader = new FileReader();
  
        reader.onloadend = function(e) {
          if (e.target.error != null) {
            showError(&quot;File &quot; + file.name + &quot; could not be read.&quot;);
            return;
          } else {
            google.script.run
              .withSuccessHandler(showSuccess)
              .uploadFileToGoogleDrive(e.target.result, file.name, $('input#name').val(), $('input#email').val());
          }
        };
  
        function showSuccess(e) {
          if (e === &quot;OK&quot;) { 
            $('#forminner').hide();
            $('#success').show();
          } else {
            showError(e);
          }
        }
  
        function submitForm() {
  
          var files = $('#files')[0].files;
  
          if (files.length === 0) {
            showError(&quot;Please select a file to upload&quot;);
            return;
          }
  
          file = files[0];
  
          if (file.size &gt; 1024 * 1024 * 5) {
            showError(&quot;The file size should be &lt; 5 MB. Please &lt;a href='http://www.labnol.org/internet/file-upload-google-forms/29170/' target='_blank'&gt;upgrade to premium&lt;/a&gt; for receiving larger files in Google Drive&quot;);
            return;
          }
  
          showMessage(&quot;Uploading file..&quot;);
  
          reader.readAsDataURL(file);
  
        }
  
        function showError(e) {
          $('#progress').addClass('red-text').html(e);
        }
  
        function showMessage(e) {
          $('#progress').removeClass('red-text').html(e);
        }
  
  
      &lt;/script&gt;
  
    &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  <p>As reccomended Im going to describe the process here.</p>
  <p>So we are on the website: <a href="http://www.example.com" rel="nofollow noreferrer">www.example.com</a> , there is a form with text input field and file field. Lets say we put in an image and call it example. Now if we press submit, I want to upload the image to google drive without any oAuth (Thats why we need to use google app script here) and name it to what we typed in the textfield. When the upload is done, I want the url of the image of google drive to be returned back to the website, so the form can continue working with the information. I want to save the returned url in a var then, to later on save it in a database. Thats why I need the result back to my website.</p>
  <p>So scheme looks like the following:</p>
  <p>Enter informations to form on website -&gt; Redirected to google app script: take informations of website form field and upload file to google drive and name it like text input entry -&gt; taking url of google drive as final result -&gt; redirecting final url result back to website -&gt; saving url result in var and continuing doing stuff from function on website -&gt; at the end saving the informations from var to a database -&gt; finish</p>
  <p>------------------------------------------------ EDIT: ------------------</p>
  <p>Thanks to @Tanaike Im a lot closer to the goal of my challenge here, so in order to see where I got stuck, I'm replicating my issue now:</p>
  <p>I took the form with the script from your example:</p>
  <pre><code>&lt;form id=&quot;form&quot;&gt;
    &lt;input name=&quot;file&quot; id=&quot;uploadfile&quot; type=&quot;file&quot;&gt;
    &lt;input name=&quot;filename&quot; id=&quot;filename&quot; type=&quot;text&quot;&gt;
    &lt;input id=&quot;submit&quot; type=&quot;submit&quot;&gt;
  &lt;/form&gt;
  &lt;script&gt;
  const form = document.getElementById('form');
  form.addEventListener('submit', e =&gt; {
    e.preventDefault();
    const file = form.file.files[0];
    const fr = new FileReader();
    fr.readAsArrayBuffer(file);
    fr.onload = f =&gt; {
      
      const url = &quot;https://script.google.com/macros/s/###/exec&quot;;  // &lt;--- Please set the URL of Web Apps.
      
      const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
      fetch(`${url}?${qs}`, {method: &quot;POST&quot;, body: JSON.stringify([...new Int8Array(f.target.result)])})
      .then(res =&gt; res.json())
      .then(e =&gt; console.log(e))  // &lt;--- You can retrieve the returned value here.
      .catch(err =&gt; console.log(err));
    }
  });
  &lt;/script&gt;
  </code></pre>
  <p>and for google script:</p>
  <pre><code>function doPost(e) {
    // const folderId = &quot;###&quot;;  // Folder ID which is used for putting the file, if you need.
  
    const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);
    const file = DriveApp.getFolderById(folderId || &quot;root&quot;).createFile(blob);
    const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};
    return ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);
  }
  </code></pre>
  <p>Now when i tried to upload something I had following error: CORS Policy not able to fetch. So I changed this part to the following and added mode no cors:</p>
  <pre><code>const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
          fetch(`${url}?${qs}`, {method: &quot;POST&quot;, mode: &quot;no-cors&quot;, body: JSON.stringify([...new Int8Array(f.target.result)])})
  </code></pre>
  <p>This worked. Second try uploading the file caused in the following error:
  it says:  <code>syntax error: unexpected end of input</code></p>
  <p>So I changed this line and removed the brackets from res.json</p>
  <pre><code>JSON.stringify([...new Int8Array(f.target.result)])})
          .then(res =&gt; res.json)
  </code></pre>
  <p>third try to upload the file actually worked with the following console result:</p>
  <pre><code>ƒ json() { [native code] }
  </code></pre>
  <p>But there is no file uploaded in google drive. Im missing something somewhere. Maybe we should create a folder and place the files in there.</p>
  <p>Oh and another information: when i run doPost function in google app sript it says:</p>
  <pre><code>TypeError: Cannot read property 'postData' of undefined (line 13
  </code></pre>
  <p>EDIT2 -----------------------------------------</p>
  <p>I added <a href="https://drive.google.com/uc?export=download&amp;id=###fileId###" rel="nofollow noreferrer">https://drive.google.com/uc?export=download&amp;id=###fileId###</a> to your code and everything works fine. The file is getting uploaded.</p>
  <p>Lets say we upload the file test.mp3 and we call it testdata.
  This is what we recieve:</p>
  <pre><code>{
    &quot;filename&quot;: &quot;testdata&quot;,
    &quot;fileId&quot;: &quot;###some id##&quot;,
    &quot;fileUrl&quot;: &quot;https://drive.google.com/uc?export=download&amp;id=###fileId###&quot;
  }
  </code></pre>
  <p>Now when I open the file url, the browser downloads file but its called: testdata, not testdata.mp3. The filetyp ending is missing.</p>
  <p>Second task: If you click the link, I want to open the file in browser, when its mp3 file for example i want that you can play the sound in webview, like it is here: <a href="https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Descalo.mp3" rel="nofollow noreferrer">https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Descalo.mp3</a></p>
  <p>I hope you can guide me!</p>