Skip to content

Instantly share code, notes, and snippets.

@nodahikaru
Last active April 8, 2020 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodahikaru/d7e572b9c65b12267dc7f739c57b5b7c to your computer and use it in GitHub Desktop.
Save nodahikaru/d7e572b9c65b12267dc7f739c57b5b7c to your computer and use it in GitHub Desktop.
File uploading in Flutter/Dart
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