title: Uploading image to Google Drive using Apps Script
body: <p>I am trying to create a function that uploads an image from the users local memory and sends it to the Google Drive connected, in apps script. I seem to be able to interact with the drive and the file, but whenever I upload the image, the google drive has a file in it with the right name but it is not an image, it seems like a text file containing all of the data of the image.</p>
  
  <p>I can't seem to tell where the error is or where things are going wrong. If someone could even give me a hint of something I need to learn or read up on so I can find my own error, or give me the answer, either way I just want to learn where I am going wrong :)</p>
  
  <p>thanks for your help</p>
  
  <p>I have read the documentation on the FileReader API believing I wasn't using the onloadend event properly, I have tried converting an image into a blob, and a string and tried to create the files from that.</p>
  
  <pre class="lang-js prettyprint-override"><code>function addImageToDrive() {
    var file = $('#capture')[0].files[0];
    var reader = new FileReader();
  
    reader.readAsDataURL(file);
  
    reader.onloadend = function(e) {
      google.script.run
        .withSuccessHandler()
        .withFailureHandler(errorAlert)
        .uploadFileToGoogleDrive("regNo","Test",e.target.result);
    });
  }
  
  </code></pre>
  
  <pre class="lang-html prettyprint-override"><code>&lt;fieldset&gt;
    &lt;div&gt;
      &lt;button type = "button" id = "submitPhoto" 
         onclick="addImageToDrive()"&gt;PHOTO&lt;/button&gt;
      &lt;input type="file" accept="image/*" capture="camera" id = "capture"&gt;
      &lt;p&gt;&lt;img src="" id="img_preview" alt="No Image Selected"/&gt;&lt;/p&gt;
    &lt;/div&gt;
  &lt;/fieldset&gt;    
  </code></pre>
  
  <pre class="lang-js prettyprint-override"><code>function uploadFileToGoogleDrive(regNo,fileName,data) {  
    try {         
      var regFolder = checkIfFolderExists(regNo);      
      // var blob = DriveApp.createFile("test File",data);
      var contentType = data.substring(5,data.indexOf(';')),
          bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
          blob = Utilities.newBlob(bytes, contentType, regNo + fileName);
  
      DriveApp.getFolderById(regFolder).createFile(blob);
  
      Logger.log("Complete");
      return "OK";      
    } catch (f) {
      Logger.log(f.toString());
      return f.toString();
    }
  }    
  </code></pre>
  
  <p>it works, but the resulting file uploaded is not an image.</p>