Google Apps脚本:UrlFetchApp发布文件

stm*_*ter 8 http-headers google-apps-script

我正在尝试通过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()
};
Run Code Online (Sandbox Code Playgroud)

我调用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}
})
Run Code Online (Sandbox Code Playgroud)

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

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

mha*_*sey 12

有一个存在的票据突出显示的文件是不是在这个非常清晰的问题

解决方案是:

将内容长度值从标题中的"content-Length"名称/值对移动到高级参数"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}
})
Run Code Online (Sandbox Code Playgroud)

编辑:添加了一个完整的示例函数来获取如下所示的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);
}
Run Code Online (Sandbox Code Playgroud)