How to upload multiple images to the Rest API in Flutter using HTTP?

10,770

Solution 1

your Image list

List<String> photos = ["path of image1","path of image2", "path of image3",];



 List<http.MultipartFile> newList = [];

      for (var img in photos!) {
        if (img != "") {
          var multipartFile = await http.MultipartFile.fromPath(
            'Photos',
            File(img).path,
            filename: img.split('/').last,
          );
          newList.add(multipartFile);
        }
      }
request.files.addAll(newList);

Solution 2

You could pass a list of files to your method, loop over to build each MultipartFile objects and add them to your MultipartRequest

Future<String> uploadMultipleImage(List<File> files, String userid) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;

// string to uri
var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");

// create multipart request
var request = new http.MultipartRequest("POST", uri);

for (var file in files) {
    String fileName = file.path.split("/").last;
    var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));

    // get file length

    var length = await file.length(); //imageFile is your image file

    // multipart that takes file
    var multipartFileSign = new http.MultipartFile('photo', stream, length, filename: fileName);

    request.files.add(multipartFileSign);
}

Map<String, String> headers = {
    "Accept": "application/json",
    "Authorization": "Bearer $value"
}; // ignore this headers if there is no authentication

//add headers
request.headers.addAll(headers);

//adding params
request.fields['id'] = userid;
// request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';

// send
var response = await request.send();

print(response.statusCode);

// listen for response
response.stream.transform(utf8.decoder).listen((value) {
    print(value);
});
}
Share:
10,770

Related videos on Youtube

Prasath
Author by

Prasath

தோல்வி நிலையென நினைத்தால் மனிதன் வாழ்வை நினைக்கலாமா &gt; Parunthaguthu Oor Kuruvi, Adangathathu En Piravi, Adanga Pala Madanga &gt; Varum, Thaduththa Adthu Udachchi Varuven, Ippo Vanthu Mothu Da, Kitta &gt; Vanthu Paru Da, Kattaruntha Kala, Nenju Mela Era Pothu Da, Thimiru Da &gt; Thimira Thimira, Nimiru Da Nilama Nilama, Unaru Da Payanam Payanam, &gt; Thodarum Da, Tha Ippo Vanthu Mothu Da, Kitta Vanthu Paru Da Paru Da, Porus ---- My Rule. Don't ask me, What is the Update or What is the Progress, However, I will be give you on correct time

Updated on June 04, 2022

Comments

  • Prasath
    Prasath over 1 year

    I want to upload multiple images into the Rest API. I tried the below code to upload a single image to the rest API. That is working fine, for multiple image selection I'm using multi_image_picker link, how can I modified below code to upload multiple images? Thank you

    Future<String> uploadSingleImage(File file,String userid) async
      {
    
        final prefs = await SharedPreferences.getInstance();
        final key = 'token';
        final value = prefs.get(key ) ?? 0;
    
        String fileName = file.path.split("/").last;
        var stream =
        new http.ByteStream(DelegatingStream.typed(file.openRead()));
    
        // get file length
    
        var length = await file.length(); //imageFile is your image file
        Map<String, String> headers = {
          "Accept": "application/json",
          "Authorization": "Bearer $value"
        }; // ignore this headers if there is no authentication
    
        // string to uri
        var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");
    
        // create multipart request
        var request = new http.MultipartRequest("POST", uri);
    
        // multipart that takes file
        var multipartFileSign = new http.MultipartFile('photo',
            stream,
            length,
            filename: fileName
        );
    
        // add file to multipart
        request.files.add(multipartFileSign);
    
        //add headers
        request.headers.addAll(headers);
    
        //adding params
        request.fields['id'] = userid;
       // request.fields['firstName'] = 'abc';
        // request.fields['lastName'] = 'efg';
    
        // send
        var response = await request.send();
    
        print(response.statusCode);
    
        // listen for response
        response.stream.transform(utf8.decoder).listen((value) {
          print(value);
        });
      }
    
    • SilenceCodder
      SilenceCodder almost 3 years
      The plugin return assets, How did you convert yours from Assets to File?
  • Prasath
    Prasath over 3 years
    Happy to see these answers I'm struggling with the multiple_image_pickers I tried several libraries. even though most of the multiple-image picker libraries wasn't working perfectly. finally, I found a library(pub.dev/packages/multi_image_picker)libraries they using Assets , so are there any way to upload assets to the Rest API ?
  • F Perroch
    F Perroch over 3 years
    Yo just have to send the files from the result of MultiMediaPicker.pickImages to the method and you're done normally
  • Abed Putra
    Abed Putra about 3 years
    add brackets [] to make multiple images like photo[].
  • abhijith k
    abhijith k over 2 years
    If your image get overrited use below code to add file path. final targetPath = dir.absolute.path + "/lookaptPostImage${now.microsecond}.jpg"; here i add a microseccond with file path then the issue will solve
  • abhijith k
    abhijith k over 2 years
    declare the now vaiable like DateTime now = DateTime.now(); above before adding the line