Razvan Cristian Lung
Razvan Cristian Lung

Reputation: 6051

Uploading file using POST request in Flutter

I'm trying to upload a video file to my server using a post request.

var file = new File(videoPath);
var uri = Uri.parse(tokenizedUri);
HttpClientRequest request = await new HttpClient().postUrl(uri);

await request.addStream(file.openRead());
var response = await request.close();

response.transform(utf8.decoder).forEach((string) {
  print(string); // handle data
});

But the server doesn't get it. Why?

Upvotes: 7

Views: 11630

Answers (2)

Khaled Mahmoud
Khaled Mahmoud

Reputation: 343

You can use the Dio package. It supports large files and works fine with me.

sendFile(String kMainUrl, XFile file) async {
    String filePath = file.path;
    String fileName = 'any name';

    try {
      FormData formData = FormData.fromMap({
        "file":
        await MultipartFile.fromFile(filePath, filename:fileName),
      });
      Response response =
      await Dio().post(kMainUrl, data: formData);
      print("File upload response: $response");
      print(response.data['message']);
    } catch (e) {
      print("Exception Caught: $e");
    }
}

Upvotes: 1

Razvan Cristian Lung
Razvan Cristian Lung

Reputation: 6051

The correct way is to use a MultipartRequest:

    var uri = Uri.parse(url);
    var request = new MultipartRequest("POST", uri);

    var multipartFile = await MultipartFile.fromPath("package", videoPath);
    request.files.add(multipartFile);

    StreamedResponse response = await request.send();
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });

Upvotes: 10

Related Questions