Create new Doc in Google drive after processing uploaded text file

I successfully upload a text file to google Drive and I have written a method that successfully translates text to pig latin. now I am attempting to create a new document in Google Drive to output the translated text. However I always receive the message: "an error Occurred" and when I check my Drive I only have the original uploaded text.

Here is my code:

function doGet(e) {

 var app = UiApp.createApplication().setTitle("Upload");
   var formContent = app.createVerticalPanel();
   formContent.add(app.createFileUpload().setName('thefile'));
   formContent.add(app.createSubmitButton('submit'));
   var form = app.createFormPanel();
   form.add(formContent);
   app.add(form);
   return app;
 }

function doPost(e) {
   // data returned is a blob for FileUpload widget
   var fileBlob = e.parameter.thefile;
   var doc = DocsList.createFile(fileBlob);

   var app = UiApp.getActiveApplication();
   //Display a confirmation message
   var label = app.createLabel('file uploaded successfully');
   app.add(label);
   return app;

  var text = doc.getDataAsString();
  Logger.log('I uploaded and my text is: ' + text);

  MakeTranslationDoc(text);
 }

function MakeTranslationDoc(passedText) 
{ 

  // Create a new Report 
  var newdoc = DocumentApp.create('Pig Latin Translation');

  newdoc.appendParagraph(ParseText(passedText));

  // Save and close the document
  newdoc.saveAndClose();
}

function ParseText(myText) 
{  
  ...convert text to piglatin...
  return results;
}

What should I do to create the new doc successfully from the uploaded text?

Answers:

Answer

Got some time to look into it again :( its a bit of a hack but should work

Here is the API Console HELP PAGE you should create a project which will require you to sign in with your google credentials. If this is the first time to you are login in to the API you will get a large button to create your first project. You should then get credentials for a web application client. The CONSUMER_KEY and CONSUMER_SECRET are found when you click on the API Access link and are called 'Client ID' and 'Client secret'.

  • Be sure to select the Drive API service.

Once the project is created, the console will appread, click on services (link on the right), scroll down and click on the Drive API toggle to enable it.

  • Using the ID of the uploaded file you can download its content using urlFetch

The file you just upload as an ID you can get it using docID = doc.getId()

  • You will need to authorise the OAuth flow

Basically the first time you run the script, it will go through authorisation flow, that will enable your application to access your drive resources, as you might see the scope selected by the app is read-only "www.googleapis.com/auth/drive.readonly" you can learn more about the Drive API HERE

  • I have done this in a Spreadsheet to view the Logger statement, surely you can port it to a non spreadsheet bound script.

Developing in spreadsheets provide better debuggin capabilities after which we can port the code to a standalone script. The difference is that to show a UI you need to call the active spreadsheet and call .show(app) on it ... info about this here : https://developers.google.com/apps-script/uiapp#DisplayingSpreadsheet

Code:

function getFileContent(docId) {

    //set up oauth for Google Drive Settings

    var oAuthConfig1 = UrlFetchApp.addOAuthService("googleDrive2");
    oAuthConfig1.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/drive.readonly");
    oAuthConfig1.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
    oAuthConfig1.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_callback=https://script.google.com/a/macros");
    oAuthConfig1.setConsumerKey(CONSUMER_KEY);
    oAuthConfig1.setConsumerSecret(CONSUMER_SECRET);

    var options1 = {oAuthServiceName:"googleDrive2", oAuthUseToken:"always", method:"GET", headers:{"GData-Version":"3.0"}, contentType:"application/x-www-form-urlencoded"};

    //set up drive file url
    var theUrl = "https://www.googleapis.com/drive/v2/files/" + docId;

    //urlFetch for drive metadat info
    var fileMetadata = "";
    try {
        var response = UrlFetchApp.fetch(theUrl,options1);
        fileMetadata = response.getContentText();
    } catch(problem) {
        Logger.log(problem.message);  
    }

    // find the download Url
    var fileDownloadUrl = Utilities.jsonParse(fileMetadata).downloadUrl;
    Logger.log(fileDownloadUrl)

    var fileContent = "";
    try {
        var response = UrlFetchApp.fetch(fileDownloadUrl,options1);

        fileContent = response.getContentText();
    } catch(problem) {
        Logger.log(problem.message);
    }
    Logger.log(fileContent);
}

Let me know how that works.

Answer

The first thing to do these days is to move to the DriveApp which is more current than the DocList.

The function which is failing is the doc.getDataAsString() which has been replaced with the doc.getAs(mimeType).

Which these two changes, and passing the document ID to the next function (lose coupling?) your code will start working

function doGet(e) {

 var app = UiApp.createApplication().setTitle("Upload");
   var formContent = app.createVerticalPanel();
   formContent.add(app.createFileUpload().setName('thefile'));
   formContent.add(app.createSubmitButton('submit'));
   var form = app.createFormPanel();
   form.add(formContent);
   app.add(form);
   return app;
 }

function doPost(e) {
   // data returned is a blob for FileUpload widget
   var fileBlob = e.parameter.thefile;
   var doc = DriveApp.createFile(fileBlob);

   var app = UiApp.getActiveApplication();
   //Display a confirmation message
   var label = app.createLabel('file uploaded successfully');
   app.add(label);

  docID = doc.getId()
  MakeTranslationDoc(docID);

  return app;
 }

function MakeTranslationDoc(docID) 
{

  var uploadedDoc =  DriveApp.getFileById(docID);
  var text = uploadedDoc.getAs(uploadedDoc.getMimeType());

  // Create a new Report 
  var newdoc = DocumentApp.create('Pig Latin Translation');

  newdoc.appendParagraph(ParseText(text));

  // Save and close the document
  newdoc.saveAndClose();
}

function ParseText(myText) 
{  
//  ...convert text to piglatin...
  return myText;
}

The important thing is not to assume you know the MimeType and to get it from the doc itself.

Let me know if you run into any issues.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.