Search code examples
flutterdarthttpflutter-httpdart-http

How to pass an image as parameter to a key in a post request Flutter?


The request body is a form-data. The request body has a key, image that expects a file (image file here). This is what I've done so far:

final response = await http.MultipartRequest(
      'POST', Uri.parse(Constant.baseUrl + 'api/patients'))
    ..headers.addAll({"Authorization": "Bearer $token"})
    ..fields.addAll({
      "first_name": firstName,
      "last_name": lastName,
      "email": email,
      "date_of_birth": dob,
      "address": address,
      "gender": gender,
      "blood_group": bg,
      "primary_phone": primaryPhone,
      "alt_phone": altPhone
    })
    ..files.add(await http.MultipartFile.fromPath(
      'image',
      image.path,
    ));

I'm attaching the postman request body here for better understanding of my question. The last key is the one I'm facing trouble with. enter image description here

I think I'm just uploading the image file without the key. That is why, my request works but the image still doesn't get posted. The image file here is a XFile (using the image_picker library in FLutter).

Also I want to achieve this using the http library. I know it is possible through dio. But just for this request, I don't want to import another library.


Solution

  • uploadTest(FilePickerResult result, String url, docname, formId,
          {lastService: false}) async {
        print(result);
        if (result != null) {
          String filename = docname;
          final file = result.files.first;
          // if (lastService == true) {
          filename = docname + '.' + file.name.split(".")[1];
          print("filename is $filename");
          // }
    
          var uri = Uri.parse(url);
          var stream = http.ByteStream(file.readStream);
          var request = http.MultipartRequest('POST', uri);
          final mimeType = lookupMimeType(file.name ?? '');
          var val1 = {
            "customerId": variableMap['customerId'],
            "FormId": formId,
            "docName": filename
          };
          final val2 = json.encode(val1);
          request.fields['val'] = val2;
          var multipartFile = http.MultipartFile(
            'myFile',
            stream,
            file.size,
            filename: filename,
            contentType: mimeType == null ? null : MediaType.parse(mimeType),
          );
    
          request.files.add(multipartFile);
          final httpClient = http.Client();
          final response = await httpClient.send(request);
          if (response.statusCode != 200) {
            throw Exception('HTTP ${response.statusCode}');
          }
    
          final body = await response.stream.transform(utf8.decoder).join();
    
          print(body);
        }
      }
    

    // I am posting the method that i used ..havenot customized as your usecase. It performs the imageupload from the filePicker