Ardabily
Ardabily

Reputation: 29

How to upload image using dart http

I'm trying to create a photo upload feature using dart http. when I run the code but it fails to upload. this is my image picker

pickImage(ImageSource source) async {
    final XFile? image = await ImagePicker().pickImage(source: source);
    if (image != null) {
      updateProfile.updateProfilePicture(File(image.path)).whenComplete(() => refresh());
    }
  }

this is my code to upload picture

Future<void> updateProfilePicture(File file) async {
    const storage = FlutterSecureStorage();
    String? token = await storage.read(key: "token");
    try {
      var headers = {
        'Authorization': 'Bearer $token',
      };

      var request = http.MultipartRequest('POST',
          Uri.parse('https://web.com/apiv1/employee/update_foto'));
      print(file.path);
      request.files.add(await http.MultipartFile.fromPath('foto', file.path));
      request.headers.addAll(headers);
      http.StreamedResponse response = await request.send();
      if (response.statusCode == 200) {
        print(await response.stream.bytesToString());
        print(response.reasonPhrase);
      } else {
        print(response.reasonPhrase);
      }
    } catch (e) {
      if (kDebugMode && e is Error) {
        print(e);
        print(e.stackTrace);
      }
    }
  }

when the code is run the response rejects because it is not an image type. but when I try print(file.path) the result is already in image format like this.

I/flutter (11417): /data/user/0/com.example.employee_self_service/cache/72cdc875-c8ef-41bb-946a-780fd613add1/1000000038.jpg

Upvotes: 0

Views: 53

Answers (1)

Olawale Ajepe
Olawale Ajepe

Reputation: 66

  • Add http parser package to be able to define MediaType

    import 'package:http_parser/http_parser.dart';

  • Convert the image (from path) to bytes by:

    request.files.add(
      http.MultipartFile.fromBytes('foto', File(file.path).readAsBytesSync(),
          filename: selfie,
          contentType: MediaType(
            'image',
            'jpeg',
          )));
    

The two Media Types defined here should work, but you can check out for more MediaType as demanded for your use case

  • Add to your header;

    var header = {
    "Content-Type": "multipart/form-data",
    "Accept": "*/*"
    

    };

Upvotes: 0

Related Questions