PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 31, 2022

[FIXED] How do I use StreamedRequest in Dart http library to upload a file?

 July 31, 2022     dart, file-upload, http, rest     No comments   

Issue

I want to upload a file via a non-multipart/form-data request like this:

POST http://127.0.0.1/upload
Cache-Control: no-cache

< /path/to/file/in/disk

(I tested and it successfully uploaded a file from JetBrain Rider's REST client to my REST endpoint.)

There is a StreamedRequest class in http package but I didn't find any constructor or setter to plug a byte stream or file content into it.

How do I use StreamedRequest to upload a file in Dart?


Solution

In some older code of mine I use

  /// Send a POST request to the Docker service.
  Future<http.ByteStream> _streamRequestStream(
      String path, Stream<List<int>> stream,
      {Map<String, String> query}) async {
    assert(stream != null);
    final url = serverReference.buildUri(path, query);
    final request = new http.StreamedRequest('POST', url)
      ..headers.addAll(headersTar);
    stream.listen(request.sink.add);
    final http.BaseResponse response =
        await request.send().then(http.Response.fromStream);
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw new DockerRemoteApiError(
          response.statusCode, response.reasonPhrase, null);
    }
    return (response as http.StreamedResponse).stream;
  }

which might do what you want

https://github.com/bwu-dart/bwu_docker/blob/master/lib/src/remote_api.dart#L160-L178

It uses the http package

import 'package:http/http.dart' as http;


Answered By - Günter Zöchbauer
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing