Google Apps 脚本:UrlFetchApp 发布文件 [英] Google Apps Script: UrlFetchApp Post File
问题描述
我正在尝试通过 Google Apps 脚本将文件发布到 REST API.这个想法是我有一个创建 Google 文档副本的过程,我希望能够将这些新创建的文档发布到第三方系统.
I'm trying to POST a file to a REST API via Google Apps Script. The idea is that I have a process that is creating copies of a Google Doc, and I want to be able to post those newly created Docs to a third party system.
我在 UrlFetchApp
中发现我可以发送文件.但是,我在发送正确的标头值时遇到了问题.
I found in UrlFetchApp
that I can send files. However, I'm having issues sending the correct header values.
我的请求看起来像这样:
My request looks like so:
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) 时的选项如下:
My options when I call UrlFetchApp.fetch(url, options) looks like :
({
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
和文件大小不匹配.
The API that I'm sending the files to requires the 'Content-Length'
header. But, when I try to set a value for 'Content-Length'
header I get an Apps Script error, "Attribute provided with invalid value: Header:Content-Length"
. If I don't set the Content-Length
header then the API responds that the Content-Length
and file size don't match.
关于如何设置 Content-Length
标头以便我可以发布文件的任何想法?
Any ideas on how I set the Content-Length
header so I can POST the file?
推荐答案
解决办法是:
将内容长度值从content-Length"名称/值对移入高级参数contentLength"的标题
Move content length value from "content-Length" name/value pair in headers to the advanced argument "contentLength"
因此在您的示例中,您的选项应如下所示
So in your example your options should look like
({
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:
Added a full example function to get contentLength and blob shown below:
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);
}
这篇关于Google Apps 脚本:UrlFetchApp 发布文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!