salk52 / flutter-file-upload-download Goto Github PK
View Code? Open in Web Editor NEWFlutter example to upload/download file with progress bar
License: GNU General Public License v3.0
Flutter example to upload/download file with progress bar
License: GNU General Public License v3.0
App Not Running
it shows error migrate to Androidx
Some Content is missing from PDF after uploading to the server but on the other side the same API with same file uploading from post-man All the content are available in the PDF.
Working Code.
_asyncFileUpload(String text, File file, int i, DocProviderBLoC doc) async {
final httpClient = getHttpClient();
var endPoint = 'uploaddocument';
final request =
await httpClient.postUrl(Uri.parse("${baseUrl()}$endPoint"));
int byteCount = 0;
request.headers.add('auth-key', UserLocalPreference.getUserToken()!);
var requestMultipart =
http.MultipartRequest("POST", Uri.parse("${baseUrl()}$endPoint"));
// requestMultipart.headers['auth-key'] = UserLocalPreference.getUserToken()!;
//add multipart to request
requestMultipart.fields['subcategory_id'] =
doc.docData[i].subcategoryId.toString();
requestMultipart.fields['doc_defination_id'] =
doc.docData[i].docDefinationId.toString();
requestMultipart.fields['name'] = doc.docData[i].name;
requestMultipart.fields['password'] = password ?? '';
requestMultipart.fields['application_id'] =
UserLocalPreference.getApplicationId()!;
debugPrint('appplication id -> ${UserLocalPreference.getApplicationId()!}');
var pic = await http.MultipartFile.fromPath("files[]", file.path);
requestMultipart.files.add(pic);
var msStream = requestMultipart.finalize();
var totalByteLength = requestMultipart.contentLength;
request.contentLength = totalByteLength;
request.headers.set(HttpHeaders.contentTypeHeader,
requestMultipart.headers[HttpHeaders.contentTypeHeader]!);
Stream<List<int>> streamUpload =
msStream.transform(StreamTransformer.fromHandlers(
handleData: (data, sink) {
debugPrint('Percentage -> ${data.length}');
sink.add(data);
byteCount += data.length;
var percentage = byteCount / totalByteLength * 100;
loadingController.forward();
debugPrint('Total ByteCount => ${percentage.floor()} % ');
debugPrint('index => $i');
setState(() {
valuePercentage = percentage / 100;
fileDownloadProgress[i] = valuePercentage;
debugPrint('downloadProgress => ${fileDownloadProgress[i]}');
});
//uploadedPercentage.add(percentage.floor().toDouble());
},
handleError: (error, stack, sink) {
throw error;
},
handleDone: (sink) {
sink.close();
// UPLOAD DONE;
},
));
await request.addStream(streamUpload);
final httpResponse = await request.close();
var statusCode = httpResponse.statusCode;
var data = httpResponse.toString();
debugPrint('Status ee code => $statusCode Data => $data');
if (statusCode ~/ 100 != 2) {
password = '';
throw Exception(
'Error uploading file, Status code: ${httpResponse.statusCode}');
} else {
var dataResponse = await readResponseAsString(httpResponse);
UploadDocumentResponse response =
UploadDocumentResponse.fromJson(jsonDecode(dataResponse));
debugPrint('dataResponse => ${response.message} ');
if (response.status!.contains('error')) {
Utils.showSnackBar(
title: response.status!,
message: response.message!,
context: context,
bgColor: AppColors.errorBgColor,
darkColor: AppColors.errorDarkColor,
);
} else {
// ignore: use_build_context_synchronously
var docProvider = Provider.of<DocProviderBLoC>(context, listen: false);
debugPrint('file -> ${file.path}');
docImage[i] = file.path;
setState(() {
docProvider.docData[i].isAllUploaded = true;
});
debugPrint('dataResponse => ${docProvider.docData[i].toJson()} ');
debugPrint(
'getAllDocStatus => ${getAllDocStatus(docProvider.docData)} ');
}
}
}
I am using your (slightly adjusted) example to upload my files, which is working great! The files are uploaded. But the onUploadProgress
is only called a few times. This makes my progress bar going from 1 percent to 100 in a matter of milliseconds (as you can see in my printouts below). This upload is a 18MB file and it jumps to 100% right away when I start the upload. After that it just waits until the full file is uploaded (even though it says 100%).
flutter: Timestamp: 27/05/2020 10:16:40
flutter: progress: 0.0000038115517316420344 (74/19414665)
flutter: Timestamp: 27/05/2020 10:16:40
flutter: progress: 0.00000880777494744308 (171/19414665)
flutter: Timestamp: 27/05/2020 10:16:40
flutter: progress: 0.999995982418445 (19414587/19414665)
flutter: Timestamp: 27/05/2020 10:16:40
flutter: progress: 0.9999960854333567 (19414589/19414665)
flutter: Timestamp: 27/05/2020 10:16:40
flutter: progress: 1.0 (19414665/19414665)
Above is from below line in just before the upload callback is called.
print('progress: ${byteCount / totalByteLength} ($byteCount/$totalByteLength)');
Below is the used code from your example. The only part I changed is the way I create the multipart
var multipart = http.MultipartFile.fromBytes(
'file',
attachment.file.buffer.asUint8List(),
filename: attachment.name,
contentType: MediaType.parse(attachment.contentType),
);
Full code:
static Future<Attachment> fileUploadMultipart({
String url,
Attachment attachment,
OnUploadProgressCallback onUploadProgress,
}) async {
assert(attachment != null);
final httpClient = getHttpClient();
final request = await httpClient.putUrl(Uri.parse(url));
int byteCount = 0;
var multipart = http.MultipartFile.fromBytes(
'file',
attachment.file.buffer.asUint8List(),
filename: attachment.name,
contentType: MediaType.parse(attachment.contentType),
);
// final fileStreamFile = file.openRead();
// var multipart = MultipartFile("file", fileStreamFile, file.lengthSync(),
// filename: fileUtil.basename(file.path));
var requestMultipart = http.MultipartRequest("", Uri.parse("uri"));
requestMultipart.files.add(multipart);
var msStream = requestMultipart.finalize();
var totalByteLength = requestMultipart.contentLength;
request.contentLength = totalByteLength;
request.headers.set(
HttpHeaders.contentTypeHeader,
requestMultipart.headers[HttpHeaders.contentTypeHeader],
);
Stream<List<int>> streamUpload = msStream.transform(
new StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data);
byteCount += data.length;
var formatter = new DateFormat('dd/MM/yyyy HH:mm:ss');
if (onUploadProgress != null) {
print('Timestamp: ${formatter.format(DateTime.now())}');
print('progress: ${byteCount / totalByteLength} ($byteCount/$totalByteLength)');
onUploadProgress(byteCount, totalByteLength);
}
},
handleError: (error, stack, sink) {
throw error;
},
handleDone: (sink) {
sink.close();
},
),
);
await request.addStream(streamUpload);
final httpResponse = await request.close();
var statusCode = httpResponse.statusCode;
if (statusCode ~/ 100 != 2) {
throw Exception('Error uploading file, Status code: ${httpResponse.statusCode}');
} else {
var data = await readResponseAsString(httpResponse);
var mapped = Attachment.fromJson(jsonDecode(data));
return mapped;
}
}
Is there are way to decrease the amount of bytes send to the server (which is a dotnet core 3.1 API) so that my progress bar is updated more fluently?
await request.addStream(streamUpload);
final httpResponse = await request.close();
addStream and close is not defined. Whats the alternative please suggest
After updating Flutter to Flutter 1.8.1-pre-11 I am getting an error in file_service.dart file. Error is in readResponseAsString method. Line 260
response.transform(utf8.decoder).listen((String data) {
The argument type 'Utf8Decoder' can't be assigned to the parameter type 'StreamTransformer<Uint8List, dynamic>'.
The argument type 'Null Function(String)' can't be assigned to the parameter type 'void Function(dynamic)'.
Can you please check it?
The Code is running very well but API response is reading ad String.
How can we read as JSON body and assign to model class.?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.