With Dart / Flutter I choose photos from the gallery. How can I send my selected photo to the c# api? I have no idea how to send the selected image to the api. Thanks for help

Api will use the selected photo according to the function of the application. The part I don't understand is; How can I send the photo to api?

Here is my code:

import 'dart:io';

        import 'package:flutter/material.dart';
        import 'package:image_picker/image_picker.dart';

        void main() {
          runApp(new MaterialApp(
            title: "Ymgk Proje",
            home: LandingScreen(),
          ));
        }

        class LandingScreen extends StatefulWidget {
          @override
          _LandingScreenState createState() => _LandingScreenState();
        }

        class _LandingScreenState extends State<LandingScreen> {
          File imageFile;

          _openGallary(BuildContext context) async {
            var picture =
                imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
            this.setState(() {
              imageFile = picture;
            });
            Navigator.of(context).pop();
          }

          _openCamera(BuildContext context) async {
            var picture =
                imageFile = await ImagePicker.pickImage(source: ImageSource.camera);

            this.setState(() {
              imageFile = picture;
            });
            Navigator.of(context).pop();
          }

          Future<void> _showChoiceDiolog(BuildContext context) {
            return showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("Ekleme yönteminizi seçiniz."),
                    content: SingleChildScrollView(
                      child: ListBody(
                        children: <Widget>[
                          GestureDetector(
                            child: Text("Galeri"),
                            onTap: () {
                              _openGallary(context);
                            },
                          ),
                          Padding(padding: EdgeInsets.all(8.0)),
                          GestureDetector(
                            child: Text("Kamera"),
                            onTap: () {
                              _openCamera(context);
                            },
                          )
                        ],
                      ),
                    ),
                  );
                });
          }

          Widget _decideImageView() {
            if (imageFile == null) {
              return Text("Henüz resim Seçilmedi!");
            } else {
              return Image.file(imageFile, width: 400, height: 400);
            }
          }

          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text("YMGK2"),
                centerTitle: mounted,
              ),
              body: Container(
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _decideImageView(),
                      RaisedButton(
                        onPressed: () {
                          _showChoiceDiolog(context);
                        },
                        child: Text("Resim Ekle"),
                      )
                    ],
                  ),
                ),
              ),
            );
          }
        }


Solution 1: Ravi Singh Lodhi

You can convert your File object i.e, imageFile into Uint8List & send it to the API.

File imageFile;

// Your code to get imageFile

// Convert imageFile to Uint8List
Uint8List uint8List = imageFile.readAsBytesSync();

// Upload data to API
Map<String, dynamic> data = {'imageFile': uint8List};

Response response = await http.post(
  '$baseUrl/api_path',
  body: jsonEncode(
    {
      'reportdata': data,
    },
  ),
  headers: {
    'Content-type': 'application/json',
    'Authorization': '$token',
  },
);
return response;


Solution 2: rasityilmaz

This my Post Method on Flutter

  Future<Object> updateUserImages(
      List<Object> files, String userID, String imageID, String token) async {
    try {
      var url = Uri.parse("$API_BASE_URL$updateUserImagesUrl?imageID=$imageID");

      var request = http.MultipartRequest("POST", url);

      request.headers['Authorization'] =
          "Bearer ${StaticServices.userBaseModel!.token!.token}";

      for (var i = 0; i < files.length; i++) {
        if (files[i] is XFile) {
          var pic = http.MultipartFile.fromBytes(
              "files", await File((files[i] as XFile).path).readAsBytes(),
              filename: '${userID}_$i',
              contentType:
                  MediaType("image", (files[i] as XFile).mimeType ?? "png"));

          //add multipart to request
          request.files.add(pic);
        } else {
          var f =
              await NetworkAssetBundle(Uri.parse(files[i] as String)).load("");
          var pic = http.MultipartFile.fromBytes(
              "files", f.buffer.asUint8List(),
              filename: '${userID}_$i',
              contentType: MediaType(
                  "image",
                  (files[i] as String)
                      .substring((files[i] as String).lastIndexOf('.') + 1)));

          //add multipart to request
          request.files.add(pic);
        }
      }

      var response = await request.send();
      var responseData = await response.stream.toBytes();
      var responseString = String.fromCharCodes(responseData);

      if (response.statusCode == 200) {
        return Success(response: Images.fromJson(jsonDecode(responseString)));
      }
      return Failure(
        errorMessage: responseString,
      );
    } on HttpException {
      return Failure(errorMessage: "No Internet Connection");
    } on FormatException {
      return Failure(errorMessage: "Invalid Format");
    } on SocketException {
      return Failure(errorMessage: "No Internet Connection");
    } catch (e) {
      return Failure(errorMessage: "Invalid Error");
    }
  }

and my API Method

public async Task<IActionResult> UpdateUserImages([FromForm] List<IFormFile> files)