2014-10-28 119 views
6

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

我在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(网址,选项)看起来像:

({ 
    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'标头设置值时,我收到一个Apps脚本错误,"Attribute provided with invalid value: Header:Content-Length"。如果我没有设置Content-Length标题,那么API响应Content-Length和文件大小不匹配。

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

回答

7

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

解决方法是:从 头 “CONTENTLENGTH” 名称/值对,以先进的变量 “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); 
} 
+0

谢谢,@mhawksey!我做了这个改变,并且出演了这个问题。更改让我通过了Google Apps脚本错误,但API现在看不到要发送的值。我仍然收到Content-Length与文件长度不匹配的消息。我现在试图查看UrlFetchApp实际发送的内容,但在Google开发工具中检查网络流量时看不到请求。有什么地方可以看到由UrlFetchApp发送的POST吗? – stmcallister 2014-10-28 18:56:50

+1

用httpbin换出服务端点应该可以工作(请参阅http://stackoverflow.com/a/9770981/1027723) – mhawksey 2014-10-28 19:16:52

+0

酷! httpbin相当有帮助!根据我的httpbin输出我的Content-Length:60的头部值。虽然,我的options.fileLength = 90665.任何想法可能导致这两个不同? – stmcallister 2014-10-28 22:01:13