Muhammad Shafique
Muhammad Shafique

Reputation: 609

How to upload File to API in Flutter WEB

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.

Upvotes: 2

Views: 3622

Answers (2)

Muhammad Shafique
Muhammad Shafique

Reputation: 609

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);
    });
  }

Upvotes: 1

Jayesh Pansheriya
Jayesh Pansheriya

Reputation: 218

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,
    );
  }
}

Upvotes: 5

Related Questions