Using Google Apps Script to upload a text file to Google Drive

It seems like uploading a file should be straightforward. However, I'm struggling with understanding blobs.

function createFileUploader() { 
  var app = UiApp.createApplication(); 
  var panel = app.createVerticalPanel().setId('panel');
  var fileUpload = app.createFileUpload().setName('uploadedFile').setId('uploadedFile');
  var handler = app.createServerChangeHandler('uploadFileHandler');
  handler.addCallbackElement(panel);
  fileUpload.addChangeHandler(handler);
  panel.add(fileUpload);
  app.add(panel);
  return app;
} 

function uploadFileHandler(e) 
{ 
// Convert uploaded data to blob format
// Assuming the uploaded file is a text file in this example
var fileBlob = Utilities.newBlob(e.parameter.uploadedFile, "text/plain","file.txt" );

    // Create a new document
var doc = DocumentApp.create('Uploaded Text File');

doc.appendParagraph(fileBlob.getDataAsString());

// Save and close the document
doc.saveAndClose();

var app = UiApp.getActiveApplication();
app.getElementById('panel').add(app.createLabel('File uploaded successfully'));
return app;
}

Every time I try to upload a file using this Google Apps Script Code, I receive an 'undefined' error. My goal is simply to upload a text file to my Google Drive.

Can anyone help me fix this code? Or perhaps suggest a better approach to accomplish this task?

Answer №1

Google Apps Script has recently introduced "Experimental" Resources for accessing Advanced Google Services. A total of 15 Advanced Services, including Drive API, can now be utilized.

To access these resources, navigate to the Resources menu:

In addition, it is necessary to enable the Drive Service in the Google Developers console.

Refer to the Google Documentation at: Advanced Drive Services

Below is a code snippet provided by Google:

function uploadFile() {
  var image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
  var file = {
    title: 'google_logo.png',
    mimeType: 'image/png'
  };
  file = Drive.Files.insert(file, image);
  Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
}

EDIT

Initially, I believed that it was not possible to upload a file from the user's computer to Google Drive using the HTML Service, but fortunately, I stand corrected! :)

File Upload with HTML Service

Answer №2

If you need to upload a file, it is important to note that utilizing a server handler will not suffice. Instead, the recommended approach is to employ a FormPanel along with a Submit button. For further assistance, refer to the FileUpload widget's documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the scope for promise .then() functions when calling a service

I've just started using AngularJS and I have a question about handling promises in controllers. In my controller, I'm calling a service that communicates with a webservice and returns a promise. I want to apply the data from the promise's s ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

What is the reason for the excessive width of the final column in this table?

I am currently working with a dataset that I am displaying using the handsontable library in the form of a table. One issue I am facing is that the last column of my table appears too wide even though I did not specify any width for it. Below you can see t ...

How to trigger a JavaScript function when the UI-Router state is switched?

Within my Angular App, I am utilizing ui-router to manage navigation and other tasks. In a separate script file, there is a function that looks like this: $(function () { function doSomething(){ if ($('.thisclass').length) { $(' ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

Route all Express JS paths to a static maintenance page

Need help with setting up a static Under construction page for an Angular Web App with Express Node JS Backend. I have a function called initStaticPages that initializes all routes and have added a new Page served via /maintenance. However, when trying to ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Having trouble with understanding the usage of "this" in nodejs/js when using it after a callback function within setTimeout

It's quite peculiar. Here is the code snippet that I am having trouble with: var client = { init: function () { this.connect(); return this; }, connect: function () { var clientObj = this; this.socket = ...

The submission form is being triggered immediately upon the page loading

I have a form on the landing page that sends parameters to Vuex actions. It functions correctly when I click the submit button and redirects me to the next page as expected. However, there seems to be a problem. Whenever I open or refresh the page, the par ...

Using JQuery to specify an attribute as "required" along with a value does not function as expected

Something seems off with this: $("#elementId").attr("required", "true"); In Chrome and Firefox, the DOM either displays required as the attribute (with no value) or required="" (empty value). Interestingly, it doesn't make a difference what value w ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...

An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it. HTML <html> <head> <link href="index.css" rel="stylesheet"> </head> <body> <div id="r ...

I would like to include the value of the "file_id" variable in the href attribute of an appended HTML element, but it seems

<div id="invite_popup"> </div> $(".invite_button2").click(function(){ var file_id = $(this).data("id"); //alert(file_id); var popup2 ='< ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Tutorial on displaying historical pricing data on a chart utilizing props in Vue Chartkick

I recently discovered a chart library called Chartkick for Vue projects. If you're interested, you can check it out here: In my project, I have data passed as props to a component. However, I encountered an issue where the prop couldn't be acces ...

Is it feasible to access reference images contained within a zip/tar file using html/javascript with the help of a library?

Although this question may appear similar to others, there is a key distinction that sets it apart. In search of request efficiency rather than space efficiency, lazy loading could be the solution. However, in situations where content needs to be quickly ...

Creating a radial progress chart using Plotly JavaScript

I recently started working with the Plotly library and now I need to display a circular progress graph in Vuejs 2, like the one shown below. While Plotly is a comprehensive tool, I have not come across an example that matches this specific design using Ja ...