upload method

Future<Map> upload({
  1. required List<TelegraphFileData> telegraphFileDatas,
  2. Client? httpClient,
  3. bool isThrowOnError = true,
  4. void onUploadProgress(
    1. int bytesCount,
    2. int totalBytes
    )?,
})

Implementation

Future<Map> upload({
  required List<TelegraphFileData> telegraphFileDatas,
  // required Uint8List blob,
  Client? httpClient,
  bool isThrowOnError = true,
  void Function(int bytesCount, int totalBytes)? onUploadProgress,
}) async {
  Uri url = Uri.parse("https://telegra.ph/upload");
  HttpClient httpClientForm = HttpClient();
  HttpClientRequest request = await httpClientForm.postUrl(url);
  MultipartRequest form = MultipartRequest("post", url);

  for (var i = 0; i < telegraphFileDatas.length; i++) {
    TelegraphFileData telegraphFileData = telegraphFileDatas[i];

    MultipartFile file = MultipartFile.fromBytes(
      "file_${i}",
      telegraphFileData.file_bytes,
      filename: telegraphFileData.file_mime,
      contentType: MediaType.parse(telegraphFileData.file_mime),
    );
    form.files.add(file);
  }

  ByteStream msStream = form.finalize();
  int totalByteLength = form.contentLength;
  request.contentLength = totalByteLength;
  request.headers.set(
    HttpHeaders.contentTypeHeader,
    form.headers[HttpHeaders.contentTypeHeader]!,
  );
  int byteCount = 0;
  Stream<List<int>> streamUpload = msStream.transform(
    StreamTransformer.fromHandlers(
      handleData: (data, sink) {
        sink.add(data);
        byteCount += data.length;
        if (onUploadProgress != null) {
          onUploadProgress(byteCount, totalByteLength);
        }
      },
      handleError: (error, stack, sink) {
        throw error;
      },
      handleDone: (sink) {
        sink.close();
      },
    ),
  );
  await request.addStream(streamUpload);
  HttpClientResponse httpResponse = await request.close();
  var statusCode = httpResponse.statusCode;
  Completer<String> completer = Completer<String>();
  StringBuffer contents = StringBuffer();
  httpResponse.transform(utf8.decoder).listen(
    (String data) {
      contents.write(data);
    },
    onDone: () => completer.complete(contents.toString()),
  );
  dynamic bodys = json.decode(await completer.future);
  if (statusCode == 200) {
    if (bodys is List) {
      List<Map> files = [];
      for (var i = 0; i < bodys.length; i++) {
        dynamic body = bodys[i];
        if (body is Map) {
          files.add({"url": "https://telegra.ph${body["src"]}"});
        }
      }

      return {
        "@type": "files",
        "total_count": files.length,
        "files": files,
      };
    }
    return {
      "@type": "error",
      ...bodys,
    };
    // return `https://telegra.ph${json[0].src}`;
    // return body;
  } else {
    if (isThrowOnError) {
      throw bodys;
    } else {
      return bodys;
    }
  }
}