Google Apps Script: UrlFetchApp Mail File

I am trying to send a file to the REST API through Google Apps Script. The idea is that I have a process for creating copies of Google Doc, and I want you to be able to publish these newly created Docs in a third-party system.

I found in UrlFetchApp that I can send files. However, I am having trouble sending the correct header values.

My query looks like this:

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

My parameters when calling UrlFetchApp.fetch (url, options) look like this:

 ({ 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} }) 

The API to which I send files requires a 'Content-Length' header. But when I try to set the value for the 'Content-Length' header, I get a Script error message, "Attribute provided with invalid value: Header:Content-Length" . If I do not set the Content-Length header, then the API responds that the Content-Length and file size do not match.

Any ideas on how I set the Content-Length header so that I can POST the file?

+6
source share
1 answer

There is an existing ticket emphasizing that the documentation is not clear on this very topic.

Decision:

Move content length value from name / value content-Length pair to headers to extended argument "contentLength"

So, in your example, your parameters 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} }) 

EDIT: Added 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); } 
+7
source

Source: https://habr.com/ru/post/977371/


All Articles