Coder Social home page Coder Social logo

salk52 / flutter-file-upload-download Goto Github PK

View Code? Open in Web Editor NEW
93.0 93.0 49.0 1.62 MB

Flutter example to upload/download file with progress bar

License: GNU General Public License v3.0

Objective-C 0.03% Dart 49.23% C# 6.59% Kotlin 0.12% Swift 1.99% PowerShell 0.19% CMake 17.17% C++ 21.73% C 1.28% HTML 1.68%

flutter-file-upload-download's People

Contributors

salk52 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

flutter-file-upload-download's Issues

Some Content are missing from PDF

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)}   ');
      }
    }
  }

How to increase amount of calls to onUploadProgress?

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?

Some methods are depricated

await request.addStream(streamUpload);
final httpResponse = await request.close();

addStream and close is not defined. Whats the alternative please suggest

Flutter 1.8.1-pre-11 issue with file_service.dart

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.