From 995da7d25576fdeaa3ea63a4ecd9b959d477f5db Mon Sep 17 00:00:00 2001 From: Christian Pauly Date: Sat, 1 Feb 2020 12:08:14 +0000 Subject: [PATCH] [Client] Upload with StreamedRequest --- lib/src/client.dart | 28 ++++++++++++++++++---------- pubspec.lock | 4 ++-- test/client_test.dart | 8 -------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/lib/src/client.dart b/lib/src/client.dart index cb97bee..35185e1 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -781,18 +781,26 @@ class Client { /// and returns the mxc url as a string. Future upload(MatrixFile file) async { dynamic fileBytes; - if (this.homeserver != "https://fakeServer.notExisting") { - fileBytes = file.bytes; + // For testing + if (this.homeserver.toLowerCase() == "https://fakeserver.notexisting") { + return "mxc://example.com/AQwafuaFswefuhsfAFAgsw"; } + Map headers = {}; + headers["Authorization"] = "Bearer $accessToken"; + headers["Content-Type"] = mime(file.path); String fileName = file.path.split("/").last.toLowerCase(); - String mimeType = mime(file.path); - print("[UPLOADING] $fileName, type: $mimeType, size: ${fileBytes?.length}"); - final Map resp = await jsonRequest( - type: HTTPType.POST, - action: "/media/r0/upload?filename=$fileName", - data: fileBytes, - contentType: mimeType); - return resp["content_uri"]; + final url = "$homeserver/_matrix/media/r0/upload?filename=$fileName"; + final streamedRequest = http.StreamedRequest('POST', Uri.parse(url)) + ..headers.addAll(headers); + streamedRequest.contentLength = await file.bytes.length; + streamedRequest.sink.add(file.bytes); + streamedRequest.sink.close(); + print("[UPLOADING] $fileName, size: ${fileBytes?.length}"); + var streamedResponse = await streamedRequest.send(); + Map jsonResponse = json.decode( + String.fromCharCodes(await streamedResponse.stream.first), + ); + return jsonResponse["content_uri"]; } Future _syncRequest; diff --git a/pubspec.lock b/pubspec.lock index 3194e8b..ac250af 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -303,7 +303,7 @@ packages: source: hosted version: "1.6.4" pedantic: - dependency: "direct main" + dependency: "direct dev" description: name: pedantic url: "https://pub.dartlang.org" @@ -492,4 +492,4 @@ packages: source: hosted version: "2.1.16" sdks: - dart: ">=2.3.0-dev.0.1 <3.0.0" + dart: ">=2.7.0 <3.0.0" diff --git a/test/client_test.dart b/test/client_test.dart index 17342de..0899686 100644 --- a/test/client_test.dart +++ b/test/client_test.dart @@ -345,14 +345,6 @@ void main() { expect(newID, "!1234:fakeServer.notExisting"); }); - test('upload', () async { - final MatrixFile testFile = - MatrixFile(bytes: [], path: "fake/path/file.jpeg"); - - final dynamic resp = await matrix.upload(testFile); - expect(resp, "mxc://example.com/AQwafuaFswefuhsfAFAgsw"); - }); - test('setAvatar', () async { final MatrixFile testFile = MatrixFile(bytes: [], path: "fake/path/file.jpeg");