Home > Back-end >  How to send Images through Multipart in Flutter
How to send Images through Multipart in Flutter

Time:05-15

I want to send three images to my server. I have tried following. There are no errors, no exception but I can't send pictures to the server. Can you help me where I am making the error?

  File? image1;

I am picking images from gallery

  Future pickImage1() async {
try {
  final image = await ImagePicker().pickImage(source: ImageSource.gallery,imageQuality: 75);
  if (image == null) return;
  final imagePermanent = await saveImagePermanently(image.path);
  setState(() => image1 = imagePermanent);
} on PlatformException catch (e) {
  print('failed to pick image $e');
}

}

It's how I am trying to send images to the server

  uploadImage1(File imageFile1,File imageFile2, File imageFile3 ) async {
var postUri = Uri.parse("https://my link");
var request =  http.MultipartRequest('POST', postUri);
request.files.add( http.MultipartFile.fromBytes("image1", imageFile1.readAsBytesSync(), filename: "Photo1.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image2", imageFile1.readAsBytesSync(), filename: "Photo2.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image3", imageFile1.readAsBytesSync(), filename: "Photo3.jpg", )); 

 await request.send().then((response) {
  if (response.statusCode == 200)
  {
    print("Uploaded");
  }
  else {
    print('error');
  }
});

}

what I got in my console is

error

Here is the button where I call this function

ElevatedButton(
              onPressed: () {
               uploadImage1(image1!, image2!, image3!);
                print('pressed');
              },
              child: const Text(' upload '),
            ),

  

CodePudding user response:

Do not use both await and then together. Just use await to wait for the execution of the asynchronous function to finish.

final response = await request.send();
if (response.statusCode == 200) {
  print("Uploaded");
} else {
  print('error');
}

CodePudding user response:

I have a sample code that uploads local images to Pl@nNet, it can be of any help to you, the output for that sample code is like this:

Start fetching...
Fetching done!

{query: {project: all, images: [dc5f659df9a4bcf90fc109830564d821], organs: [leaf],
...
{id: 6411486}}], version: 2022-02-14 (5.1), remainingIdentificationRequests: 197}

Done!
  • Related