0

I need to upload a PDF file to the server.

I use this code.

  void pickFiles() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: false,
        type: FileType.custom,
        withData: true,
        allowedExtensions: ['pdf'],
      );

      Uint8List? fileBytes = result!.files.first.bytes;
      base64String = base64Encode(fileBytes!);
      nameDocumentController.text = result.files.first.name;
    } on PlatformException catch (e) {
      debugPrint('Unsupported operation$e');
    } catch (e) {
      debugPrint(e.toString());
    }
  }

I don't understand why this code doesn't work. On the server I find the file but with 0 bytes

I tried all the examples online but in the end base64String is always empty.

Where can I find a working example?

Thanks

Biagio

1 Answer 1

0

Let me show you the code I use to upload a file in PDF format to Firebase.

These are the necessary variables.

  Uint8List? fileBytes;
  String fileUploadName = "";

I am using the selectFile function to pick a PDF file with a maximum size of 50 MB.

Future selectFile() async {
    final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['pdf'],
        allowMultiple: false);

    if (result == null) {
      return;
    } else {
      final file = result.files.first;
      const maxSize = 50 * 1024 * 1024;
      if (file.size > maxSize) {
        fileSizeErrorDialog();
        return;
      }
      if (file.extension != 'pdf') {
        showPdfFormatErrorDialog();
        return;
      }

      fileBytes = file.bytes;
      fileUploadName = file.name;
    }
  }

I use the uploadFile function to upload it to Firebase. The fileBytes variable is important here as it holds the file data.

Future uploadFile(
  Uint8List? fileBytes,
  String fileUploadName,
  String uuid, {
  bool isAnnouncement = false,
}) async {
  try {
    if (fileBytes == null) {
      throw 'didntSelectFile'.tr;
    }
    if (isAnnouncement) {
      await firebaseStorage
          .ref('announcement/$uuid/$fileUploadName')
          .putData(fileBytes);
      return;
    }
    await firebaseStorage.ref('uploads/$uuid/$fileUploadName').putData(fileBytes);
  } catch (e) {
    throw '${'errorUploadingFile'.tr} : $e';
  }
}

I hope this example helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.