处理上传的文本文件后,在Google驱动器中创建新文档 [英] Create new Doc in Google drive after processing uploaded text file

查看:109
本文介绍了处理上传的文本文件后,在Google驱动器中创建新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地将文本文件上传到Google云端硬盘,并且我已经编写了一种将文本成功翻译为拉丁文的方法。现在我试图在Google云端硬盘中创建一个新文档来输出翻译文本。然而,我总是收到消息:发生错误,当我检查我的驱动器时,我只有原始上传的文本。



这是我的代码:


$ b $ pre $ 函数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);
返回应用程序;


函数doPost(e){
//返回的数据是FileUpload小部件的一个blob
var fileBlob = e.parameter.thefile;
var doc = DocsList.createFile(fileBlob);

var app = UiApp.getActiveApplication();
//显示确认信息
var label = app.createLabel('file uploaded successfully');
app.add(label);
返回应用程序;

var text = doc.getDataAsString();
Logger.log('我上传了,我的文本是:'+ text);

MakeTranslationDoc(text);
}

函数MakeTranslationDoc(passedText)
{

//创建一个新报表
var newdoc = DocumentApp.create('Pig拉丁语翻译');

newdoc.appendParagraph(ParseText(passedText));

//保存并关闭文档
newdoc.saveAndClose();
}

函数ParseText(myText)
{
...将文本转换为明胶...
返回结果;
}

我应该如何从上传的文本中成功创建新文档?

解决方案

有一些时间再次研究它(它有点黑客但应该工作)




以下是API控制台帮助页面您应该创建一个项目,这将需要您使用您的Google凭据登录。如果这是您第一次登录API,您将获得一个大按钮来创建您的第一个项目。您应该获取Web应用程序客户端的凭据。当您点击API访问链接时会找到CONSUMER_KEY和CONSUMER_SECRET,并称为客户端ID和客户端密码。




  • 确保选择Drive API服务。




项目创建完成后,控制台将会应用,点击服务(右侧的链接),向下滚动并点击Drive API切换至启用它。





  • 使用上传文件的ID,您可以使用urlFetch下载它的内容




您只需将文件上载为可使用docID = doc.getId()





  • 您需要授权OAuth流程




基本上,第一次运行脚本时,它将通过授权流程,这将使您的应用程序能够访问您的驱动器资源,就像您看到的该应用程序是只读的www.googleapis.com/auth/drive.readonly,您可以了解有关Drive API的更多信息这里





  • 我已在电子表格中完成此操作以查看Logger语句,当然,您可以将它移植到非电子表格绑定脚本。 blockquote>

    在电子表格中开发提供更好的调试功能,之后我们可以将代码移植到独立脚本中。区别在于,要显示一个UI,您需要调用活动电子表格并在其上调用.show(app)...有关此信息: https://developers.google.com/apps-script/uiapp#DisplayingSpreadsheet


    代码:

      function getFileContent(docId){

    //设置oauth对于Google云端硬盘设置

    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);
    $ b $ var options1 = {oAuthServiceName:googleDrive2,oAuthUseToken:always,方法:GET,头文件:{GData-Version:3.0},contentType:application / x -www窗体-urlencoded};

    //设置驱动器文件url
    var theUrl =https://www.googleapis.com/drive/v2/files/+ docId;

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

    //找到下载地址
    var fileDownloadUrl = Utilities.jsonParse(fileMetadata).downloadUrl;
    Logger.log(fileDownloadUrl)

    var fileContent =;
    尝试{
    var response = UrlFetchApp.fetch(fileDownloadUrl,options1);

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

    让我知道它是如何工作的。


    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?

    解决方案

    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.

    这篇关于处理上传的文本文件后,在Google驱动器中创建新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆