2014-10-28 184 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

相關問題