Last active
April 8, 2020 14:35
-
-
Save nodahikaru/d7e572b9c65b12267dc7f739c57b5b7c to your computer and use it in GitHub Desktop.
File uploading in Flutter/Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:core'; | |
import 'dart:io'; | |
import 'package:http/http.dart' as http; | |
typedef OnUploadProgressCallback = void Function(int sentBytes, int totalBytes); | |
Future<String> fileUpload({@required File file, OnUploadProgressCallback onUploadProgress}) async { | |
assert(file != null); | |
final HttpClient httpClient = getHttpClient(); | |
final Uri uri = Uri.https('api.4d.customers.cloud54.de', '/users/avatar'); | |
final HttpClientRequest request = await httpClient.postUrl(uri); | |
int byteCount = 0; | |
final http.MultipartFile multipart = await http.MultipartFile.fromPath('file', file.path); | |
final http.MultipartRequest requestMultipart = http.MultipartRequest('', Uri.parse('uri')); | |
requestMultipart.files.add(multipart); | |
final http.ByteStream msStream = requestMultipart.finalize(); | |
final int totalByteLength = requestMultipart.contentLength; | |
request.contentLength = totalByteLength; | |
request.headers.set(HttpHeaders.contentTypeHeader, requestMultipart.headers[HttpHeaders.contentTypeHeader]); | |
request.headers.set('Authorization', 'Bearer ${my_client.HttpClient.token}'); | |
final Stream<List<int>> streamUpload = msStream.transform( | |
StreamTransformer<List<int>, List<int>>.fromHandlers( | |
handleData: (List<int> data, EventSink<List<int>> sink) { | |
sink.add(data); | |
byteCount += data.length; | |
if (onUploadProgress != null) { | |
onUploadProgress(byteCount, totalByteLength); | |
} | |
}, | |
handleError: (Object error, StackTrace stack, EventSink<List<int>> sink) { | |
throw error; | |
}, | |
handleDone: (EventSink<List<int>> sink) { | |
sink.close(); | |
} | |
) | |
); | |
await request.addStream(streamUpload); | |
final HttpClientResponse httpResponse = await request.close(); | |
final int statusCode = httpResponse.statusCode; | |
if (statusCode ~/ 100 != 2) { | |
throw Exception('Error uploading file, Status code: ${httpResponse.statusCode}'); | |
} else { | |
return await readResponseAsString(httpResponse); | |
} | |
} | |
static Future<String> readResponseAsString(HttpClientResponse response) { | |
final Completer<String> completer = Completer<String>(); | |
final StringBuffer contents = StringBuffer(); | |
response.transform(utf8.decoder).listen((String data) { | |
contents.write(data); | |
}, onDone: () => completer.complete(contents.toString())); | |
return completer.future; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment