Search code examples
file-uploaddartserver-side

Send a file via POST using Dart (server-side only)


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?


Solution

  • 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.