Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file using POST request in Flutter

Tags:

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?

like image 335
Razvan Cristian Lung Avatar asked Dec 27 '17 22:12

Razvan Cristian Lung


2 Answers

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);
    });
like image 123
Razvan Cristian Lung Avatar answered Oct 07 '22 04:10

Razvan Cristian Lung


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");
    }
}
like image 31
Khaled Mahmoud Avatar answered Oct 07 '22 02:10

Khaled Mahmoud