javascript - 处理上传的文本文件后在 Google 云端硬盘中创建新文档

标签 javascript google-apps-script runtime-error google-apps

我成功地将文本文件上传到谷歌云端硬盘,并且我编写了一个可以成功将文本翻译为 pig 拉丁语的方法。现在我尝试在 Google Drive 中创建一个新文档来输出翻译后的文本。但是,我总是收到消息:“发生错误”,当我检查我的云端硬盘时,我只有原始上传的文本。

这是我的代码:

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;
}

我应该怎样做才能从上传的文本成功创建新文档?

最佳答案

有时间再研究一下:(它有点黑客,但应该可以工作

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'.

  • 请务必选择 Drive API 服务。

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.

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

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

  • 您需要授权 OAuth 流程

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

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

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

代码:

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);
}

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

关于javascript - 处理上传的文本文件后在 Google 云端硬盘中创建新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18710624/

相关文章:

javascript - 相当于用数字键拼接一个对象

javascript - 在 Polymer 元素中使用 JavaScript

javascript - Greasemonkey 如何与 NoScript 等 javascript 拦截器交互?

python - 无法访问谷歌电子表格

google-apps-script - Google Apps 脚本中国防部网站的 SSL 验证

java - MainActivity 类型的层次结构不一致。为什么?

C - 打印字符串时出现运行时错误(使用指针)

javascript - requirejs:为什么模块中定义的函数无法访问 require() 内的局部变量,我该如何实现这一点?

google-apps-script - 谷歌日历无法通过 ID 删除事件

feed - Web 平台安装程序 - 未找到 ProductId NETFramework4