upload method

Future<bool> upload(
  1. Stream<List<int>> stream,
  2. int length
)

Uploads a file from a Stream, returns true if successful.

Implementation

Future<bool> upload(Stream<List<int>> stream, int length) async {
  if (_attemptedUpload) {
    throw Exception(
        'Data has already been uploaded using this FileUploader.');
  }
  _attemptedUpload = true;

  if (_uploadDescription.type == _UploadType.binary) {
    try {
      var result = await http.post(
        _uploadDescription.url,
        body: await _readStreamData(stream),
        headers: {
          'Content-Type': 'application/octet-stream',
          'Accept': '*/*',
        },
      );
      return result.statusCode == 200;
    } catch (e) {
      return false;
    }
  } else if (_uploadDescription.type == _UploadType.multipart) {
    // final stream = http.ByteStream(Stream.castFrom(file.openRead()));
    // final length = await file.length();

    // final stream = http.ByteStream.fromBytes(data.buffer.asUint8List());
    // final length = await data.lengthInBytes;

    var request = http.MultipartRequest('POST', _uploadDescription.url);
    var multipartFile = http.MultipartFile(
        _uploadDescription.field!, stream, length,
        filename: _uploadDescription.fileName);

    request.files.add(multipartFile);
    for (var key in _uploadDescription.requestFields.keys) {
      request.fields[key] = _uploadDescription.requestFields[key]!;
    }

    try {
      var result = await request.send();
      // var body = await _readBody(result.stream);
      // print('body: $body');
      return result.statusCode == 204;
    } catch (e) {
      return false;
    }
  }
  throw UnimplementedError('Unknown upload type');
}