Ad

Error Uploading File To Server With Flutter

- 1 answer

I have a flutter application that select and upload audio file to server with asp.net rest api.

my flutter code as follows

 uploadFile() async {
    print(file.path);
    var postUri = Uri.parse("http://192.168.1.100:5041/api/fileup/up");
    var request = new http.MultipartRequest("POST", postUri);
    request.fields['user'] = 'blah';
    request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri(Uri.parse(file.path)).readAsBytes(),contentType: MediaType('audio','mp3')
    ));

    request.send().then((response) {
      if (response.statusCode == 200) {
        print("Uploaded!");
      }else{
        print(response.reasonPhrase);
      }
    });
  }

my file.path value for above flutter code is "/data/user/0/com.mydomain.myappname/cache/file_picker/Over_the_Horizon.mp3" which is returned from file picker.

I am able to upload file with postman, but flutter code gives me 500: Internal Server Error

Postman Screenshot enter image description here

tried with several codes found on stack overflow , all gave me same error

Ad

Answer

Did you tried with DIO?

You can accomplish this with DIO, like this:

FormData formData = new FormData.fromMap({
    "file": await MultipartFile.fromFile(file.path,
        filename: file.path.split('/').last)
  });
await dio.post('http://192.168.1.100:5041/api/fileup/up', data: formData, onSendProgress: (int begin, int end) {
  var initial = begin;
  var done = end;
  print('$initial $end');
});
Ad
source: stackoverflow.com
Ad