Search code examples
flutterdartfile-upload

How to upload multiple Images through Api


I am trying to Upload Multiple Images through Api but i am not understanding how to send a list, I can upload a single image though. Tried alot of searches but does'nt helped, i also import multi_image_picker i can pick the images but the problem is in uploading.

  Future<Map<String, dynamic>> _uploadImage(File image) async {
   

    String value = '';
    SharedPreferences pref2 = await SharedPreferences.getInstance();
    value = pref2.getString("user_role");

    final mimeTypeData =
        lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');

    // Intilize the multipart request
    final imageUploadRequest = http.MultipartRequest('POST', apiUrl);

    // Attach the file in the request
    final file = await http.MultipartFile.fromPath('photo', image.path,
        contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
    // Explicitly pass the extension of the image with request body
    // Since image_picker has some bugs due which it mixes up
    // image extension with file name like this filenamejpge
    // Which creates some problem at the server side to manage
    // or verify the file extension


    imageUploadRequest.files.add(file);
    imageUploadRequest.fields['mobile'] = _mobileNo.text;

    imageUploadRequest.headers.addAll({
      'Content-Type': 'application/json',
      'Authorization': Constants.authToken,
    });

    var response = await imageUploadRequest.send();
    if (response.statusCode == 200) print('Done!');

    final respStr = await response.stream.bytesToString();

    return json.decode(respStr);
  }

Solution

  • this an example of uploading files to your API with HTTP package

    import 'package:http/http.dart' as http;
    
    void uploadFiles(List<File> files) async {
      final url = YOUR-API-LINK;
    
      for (var file in files) {
        // Create a multipart request
        var request = http.MultipartRequest('POST', Uri.parse(url));
    
        // Add the file to the request
        request.files.add(http.MultipartFile.fromBytes(
          'file',
          file.readAsBytesSync(),
          filename: file.path.split('/').last,
        ));
    
        // Send the request
        var response = await request.send();
    
        // Check the status code
        if (response.statusCode != 200) {
          print('Failed to upload file');
        }else{
        print response.body;
    }
      }
    }
    

    for Dio use this

    void uploadFiles(List<File> files) async {
      final url = YOUR-API-LINK;
    
      // Create a Dio client
      var dio = Dio();
    
      // Create a FormData object
      var formData = FormData();
    
      // Add the files to the FormData object
      for (var file in files) {
        formData.files.add(MapEntry(
          'file',
          await MultipartFile.fromFile(file.path, filename: file.path.split('/').last),
        ));
      }
    
      // Send the request
      var response = await dio.post(url, data: formData);
    
      // Check the status code
      if (response.statusCode != 200) {
        print('Failed to upload files');
      }else {
       print(response.data)
       }
    }
    

    as you can see there not much difference between them in http you use MultipartRequest in dio you use FormData.