2

I'm new to Flutter and I'm facing an issue while uploading File to API. I have tried using FormData and MultiPartFile but it return error. I have also used code in this video but it doesn't work:

https://www.youtube.com/watch?v=c2tGUt7FLqY&t=318s

Anybody have the solution.

2 Answers 2

5

Ok, I found it, leaving here for someone having the same problem

if (result != null) {    
  for (var file in result.files) {
    final formData = FormData.fromMap({
      ...someOtherData,
      'file': MultipartFile.fromBytes(file.bytes as List<int>)
    });
    
    dio.post(
      url,
      data: formData,
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I figured it out. We cannot use "File" because it use "dart.io" library which is not supported in Flutter WEB. So we have to use "Platform File" which use 'dart.html' library which is supported in Flutter WEB. Here is the code:

addStudent(
      {@required token,
      @required name,
      @required email,
      @required password,
      @required rollNo,
      @required phoneNo,
      @required PlatformFile? image,
      @required gender}) async {

    http.MultipartRequest request = http.MultipartRequest(
      "POST",
      Uri.parse('Your URL HERE'),
    );
    request.headers['Authorization'] = 'Bearer $token';

    request.fields['name'] = name;
    request.fields['email'] = email;
    request.fields['password'] = password;
    request.fields['gender'] = gender;
    request.fields['rollno'] = rollNo;
    request.fields['phoneNumber'] = phoneNo;

// Here is the code to upload image to API

    request.files.add(new http.MultipartFile(
        'image', image!.readStream!, image.size,
        filename: image.name));

    //-------Send request
    await request.send().then((value) async {
      //------Read response
      String result = await value.stream.bytesToString();

      //-------Your response
      print(result);
    });
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.