I have to send a png/jpg image to the server in the binary string form. It is also specified in the Swagger that content-type of the request has to be “multipart/form-data”.
I select images using ImagePicker package and then convert the image to base64Encoded string:
var photoAsBytes = await profilePhoto.readAsBytes();
List<int> photoAsIntList = photoAsBytes.toList();
String base64EncodedPhoto = base64Encode(photoAsIntList);
RequestResult? reqResult = await UserApiRequest.addUserPhoto(
base64EncodedPhoto
);
After that I’m sending http request:
String apiBaseUrl = SecretService.instance.apiBaseUrl;
Uri requestPath = Uri.parse("$apiBaseUrl$requestUrl");
var request = MultipartRequest("POST", requestPath);
request.headers.addAll(requestHeaders);
var imageFile = MultipartFile.fromString(
"file",
requestBody as String,
contentType: MediaType("multipart", "form-data")
);
request.files.add(imageFile);
Response response = await Response.fromStream(await request.send());
print("Result: ${response.statusCode}");
I should get a path for the image as the response from server but I get “InvalidFile” error in the service response. What am I doing wrong?