简体   繁体   中英

Upload text file to Google Drive with Google Apps Script

Seems like this should be easier. But admittedly I don't understand blobs.

function doGet(e) { 
  var app = UiApp.createApplication(); 
  var panel = app.createVerticalPanel().setId('panel');
  var fileUpload = app.createFileUpload().setName('theFile').setId('theFile');
  var handler = app.createServerChangeHandler('uploadfile');
  handler.addCallbackElement(panel);
  fileUpload.addChangeHandler(handler);
  panel.add(fileUpload);
  app.add(panel);
  return app;
} 

function uploadfile(e) 
{ 
// data returned which can be used to create a blob
// assuming mime-type to be a text file in this example
  var fileBlob = Utilities.newBlob(e.parameter.thefile, "text/plain","file.txt" );

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

    doc.appendParagraph(fileBlob.getDataAsString());

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

  //var doc = DocsList.createFile(fileBlob.getDataAsString());
  var app = UiApp.getActiveApplication();
  app.getElementById('panel').add(app.createLabel('File Uploaded successfully'));
  return app;
}

I keep getting undefined returned when I attempt to upload a file using this Google Apps Script Code. All I want to do is upload a text file to my Google Drive.

What should I do to fix this code? or is there a better way to do this?

Google Apps Script now has "Experimental" Resources to Advanced Google Services . I counted 15 Advanced Services, including Drive API .

在此处输入图片说明

Click the Resources menu:

在此处输入图片说明

You must also go to the Google Developers console, and enable Drive Service there also.

The Google Documentation is at: Advanced Drive Services

开发者控制台

Here is some sample code from 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

I thought there was no way to upload a file from the users computer to Google drive using the HTML Service, but luckily I'm wrong again! :)

File Upload with HTML Service

To do a file upload, you cannot use a server handler. You must use a FormPanel and a Submit button. See the FileUpload widget's documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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