postFile method

Future<Response> postFile(
  1. String url,
  2. File file, {
  3. HttpOptions? options,
})

Implementation

Future<Response> postFile(
  String url,
  File file, {
  HttpOptions? options,
}) async {
  var request = MultipartRequest(
    'POST',
    Uri.parse(url),
    onUploadProgress: options?.onUploadProgress,
  );
  var part = await http.MultipartFile.fromPath('file', file.path);
  Map<String, String> headers = await getHeaders(options, isFile: true);
  for (var key in headers.keys) {
    request.headers[key] = headers[key]!;
  }
  request.files.add(part);

  // Both stages are bounded, and by the upload timeout rather than the API
  // one. `send` resolves as soon as the response *headers* arrive, so the read
  // below used to have no ceiling at all: a server that answered and then
  // stalled left the caller waiting forever - the exact failure the timeout
  // was added to prevent.
  http.StreamedResponse response = await _client
      .send(request)
      .timeout(_uploadTimeout);

  var jsonString = await response.stream.bytesToString().timeout(
    _uploadTimeout,
  );

  // Through the same handler as every other request. Parsing the body
  // regardless of status turned a 401 into "Null is not a subtype of String"
  // and an HTML error page into a FormatException, both of which read as SDK
  // bugs rather than a failed upload.
  return Response.fromJson(
    asJsonObject(
      HttpService.handleResponse(
        http.Response(jsonString, response.statusCode),
      ),
      'An upload response',
    ),
  );
}