Create new Doc in Google drive after processing uploaded text file

回眸只為那壹抹淺笑 提交于 2019-12-02 03:00:51

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!