0

So I'm trying to send an image and two other strings to the server as a multipart file.Below is my function to send the files to the server. But when I try to send I get XMLHttpRequest error.Here I'm not sending any headers...I'm assuming that might be the reason.How to add headers to a multipart request? Please help me!!!

  Future<ApiResponse> postFile(String url, Map<String, String> body, List<http.MultipartFile> files) async {
logger.i('Api Post, url $_url$url');
logger.i('Api Post, data $body');

ApiResponse apiResponse;
try {
  var request = http.MultipartRequest('POST', Uri.parse(_url + url));
  request.fields.addAll(body);
  request.files.addAll(files);
  logger.i(request.headers);
  final response = await request.send();
  logger.i(response.statusCode);
  apiResponse = await _returnStreamedResponse(response);
} on SocketException {
  logger.e('No net');
  throw FetchDataException('No Internet connection');
}
return apiResponse;
}

1 Answers1

0

To pass header you have to create one more MultipartRequest and using of that you can pass header. Please check below code. I hope this will help you.

var uriRequest = http.MultipartRequest('POST',
    Uri.parse('YOUR_URI'));
var multipartFile = await http.MultipartFile
    .fromPath('', filename: imagePath.split("/").last, imagePath);

uriRequest.files.add(multipartFile);
uriRequest.headers.addAll('YOUR_HEADER);
try {
  var response = await uriRequest.send();
  if (response == null) return null;
  final respStr = await response.stream.bytesToString();
  log('Images Response :------>  $respStr');
suraj
  • 641
  • 1
  • 7
  • 15