0

I saw this SO thread to upload a file using UrlFetchApp.
Also I saw this SO thread to post a string as file in python requests (without having a file or creating a temp file).

I want to send a string as file in Google Spreadsheet Script, and based on the two threads above I think it should be possible to do it without creating a temp file in google drive.

My question is how in Google Spreadsheet Script I can pretend the string is coming from a file and pass it to UrlFetchApp?

Here is the base code I am working on:

  var string = 'test';
  var url = "https://api.telegram.org/.../sendDocument";

  var chat_id = "12345";

  var data = {'chat_id': chat_id, 
              'text':text}  ;

  var headers = { "Accept":"application/json", 
                  "Content-Type":"application/json"
                };

  var options = { "method":"POST",
                "headers": headers,
                "payload" : payload
               };

  var response = UrlFetchApp.fetch(url, options);
Community
  • 1
  • 1
apadana
  • 13,456
  • 15
  • 82
  • 98
  • 1
    You can create a [new blob](https://developers.google.com/apps-script/reference/utilities/utilities#newBlob(Byte,String)) from a string and pass the blob as file, based on your first so post. However, you will have to check the api document of the service you are calling to figure out what how to send a file, in the request of url fetch – Jack Brown Apr 26 '17 at 13:29
  • @JackBrown Thanks! Your comment was really helpful. I was able to make it work. Posted the answer below. – apadana Apr 26 '17 at 14:00

1 Answers1

1

Here is how I got it right to post a string as file:

 var url = "https://api.telegram.org/.../sendDocument";
 var blob = Utilities.newBlob('Test!', 'text/plain', 'report.txt');
 var data = {
   'chat_id' : '12345',
   'document': blob
 };
  var options = {
     'method' : 'POST',
     'payload' : data,
 };

 UrlFetchApp.fetch(url, options);

Thanks to comment from @Jack Brown and google developer example for posting blobs (example titled: Make a POST request with form data.).

apadana
  • 13,456
  • 15
  • 82
  • 98