Google Apps脚本:UrlFetchApp发布文件

时间:2014-10-28 18:14:25

标签: google-apps-script http-headers

我正在尝试通过Google Apps脚本将文件发布到REST API。我的想法是,我有一个创建Go​​ogle Doc副本的流程,我希望能够将这些新创建的Doc发布到第三方系统。

我在UrlFetchApp发现我可以发送文件。但是,我在发送正确的标头值时遇到问题。

我的要求如下:

var file = DriveApp.getFileById(fileId);
var body = {
  "file": file.getAs(MimeType.PDF)
};
var headers = {
  'Content-Disposition': 'attachment; filename="'+ file.getName() +'"',
  'Content-Length': file.getSize()
};

我调用UrlFetchApp.fetch(url,options)时的选项如下:

({
  method:"POST", 
  headers:{
      'Content-Disposition':"attachment; filename=\"My Merge Development_row_1.pdf\"", 
      'Content-Length':90665, 
       Authorization:"Bearer TOKEN"
  }, 
  contentType:"application/x-www-form-urlencoded", 
  muteHttpExceptions:true, 
  payload:{file:Blob}
})

我发送文件的API需要'Content-Length'标头。但是,当我尝试为'Content-Length'标头设置值时,我收到了应用程序脚本错误"Attribute provided with invalid value: Header:Content-Length"。如果我没有设置Content-Length标头,则API会响应Content-Length和文件大小不匹配。

关于如何设置Content-Length标题的任何想法,以便我可以发布文件?

1 个答案:

答案 0 :(得分:12)

有一个existing ticket highlighting that the documentation is not clear on this very issue

解决方案是:

  

从"内容长度"移动内容长度值名称/值对   高级参数的标题" contentLength"

因此,在您的示例中,您的选项应该类似于

({
  method:"POST", 
  headers:{
      'Content-Disposition':"attachment; filename=\"My Merge Development_row_1.pdf\"", 
       Authorization:"Bearer TOKEN"
  }, 
  contentLength: 90665,
  contentType:"application/x-www-form-urlencoded", 
  muteHttpExceptions:true, 
  payload:{file:Blob}
})

编辑:添加了一个完整的示例函数来获取如下所示的contentLength和blob:

function testFilePost() {
  var file = DriveApp.getFileById(doc_id).getAs(MimeType.PDF);
  var headers = {
    'Content-Disposition': 'attachment; filename="'+ file.getName() +'"',
  };
  var options =
      {
        "method" : "post",
        "payload": file.getBytes(),
        "headers": headers,
        "contentLength": file.getBytes().length,
      };
  var result = JSON.parse(UrlFetchApp.fetch('http://httpbin.org/post', options).getContentText());
  Logger.log(result);
}