0

I am developing a Telegram Bot, and I need to send a file via POST as attachment to an user (e.g. a .txt file). Upon this, I have two questions:

  • Which file type should I use in order to send a file? I heard about Stream, but I am unsure about it;
  • Having the right file type, how can I send it as a parameter for the url POST? I tried the http library and built-in solutions.

    Here is a snippet of the code I'm using right now:

    Future<dynamic> sendRequest(String method, url, {json}) async {
        BaseClient bs = new IOClient();
        var request = new Request(method, url);
        request.headers['Content-Type'] = 'application/json';
        request.body = JSON.encode(json);
        var streamedResponse = await bs.send(request);
        var response = await Response.fromStream(streamedResponse);
    
        var bodyJson;
        try {
          bodyJson = JSON.decode(response.body);
        } on FormatException {
          var contentType = response.headers['content-type'];
          if (contentType != null && !contentType.contains('application/json')) {
            throw new Exception(
                'Returned value was not JSON. Did the uri end with ".json"?');
          }
          rethrow;
        }
    
        if (response.statusCode != 200) {
          if (bodyJson is Map) {
            var error = bodyJson['error'];
            if (error != null) {
              throw error;
            }
          }
          throw bodyJson;
        }
    
        return bodyJson;
    }
    

Any ideas?

muniz95
  • 13
  • 2
  • What format is the data to be sent? Is it always text based? What size is the data? I assume you are reading it from a file, but is it short enough that you can reasonably read it into a string? – Argenti Apparatus Mar 06 '17 at 14:21
  • I have many situations: the file can be an audio, a video, etc. Let's say I have a .mp4 file sized 5MB. In this case, how can I submit the file via POST request? – muniz95 Mar 06 '17 at 15:39

1 Answers1

1

I infer that you are using the Dart Pub http package. Briefly looking at the documentation it appears that both multi part and streaming uploads are supported. See the MultipartRequest and StreamedRequest classes. (I have not used these myself but they seem straightforward.)

https://www.dartdocs.org/documentation/http/0.11.3%2B9/http/http-library.html

This question may help with understanding HTTP multipart/form-data file uploads. How does HTTP file upload work?. Others may be able to point to a good resource on streaming uploads.

Argenti Apparatus
  • 3,857
  • 2
  • 25
  • 35
  • I am still facing many problems whit file uploading, but your answer helped me a lot. Thank you. – muniz95 Mar 10 '17 at 19:05