1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] unable to download pdf from mariadb using flutter

Discussão em 'Mobile' iniciado por Stack, Outubro 3, 2024 às 22:13.

  1. Stack

    Stack Membro Participativo

    I am having a hard time downloading a pdf from mariadb. I can download the json file without any issues.

    This is what I see in the Mariadb database. I am storing the attachment data in a longblob.

    SELECT sys_data FROM sys_attachment_data; +---------------------------------------------------------------------------------------------------+ | sys_data | +---------------------------------------------------------------------------------------------------+ | (16)[123, 34, 110, 97, 109, 101, 34, 58, 34, 74, 85, 65, 78, 34, 125, 10] | | (11702)[37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 211, 235, 233, 225, 10, 49, 32, 48, 32, 111, ...] | +---------------------------------------------------------------------------------------------------+

    I think I am storing a byte array but I am not sure why there is a (16) and (11702) in front of the data.

    for some reason my app does not like downloading longblob, so I had to change the method in my server to get the data from the database. this is the method that fetches the data from the database::


    public static Map<String, Object> get_records(String query_string) {
    List<Map<String, Object>> results = new ArrayList<>();

    try (Connection connection = data_source.getConnection();
    PreparedStatement statement = connection.prepareStatement(query_string)) {

    ResultSet resultSet = statement.executeQuery();
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();

    while (resultSet.next()) {
    Map<String, Object> record = new HashMap<>();
    for (int i = 1; i <= columnCount; i++) {
    String columnLabel = metaData.getColumnLabel(i);
    Object columnValue;

    // Check if the column is a BLOB and handle it accordingly
    if (metaData.getColumnType(i) == java.sql.Types.BLOB || metaData.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
    byte[] blobData = resultSet.getBytes(i);
    if (blobData != null) {
    columnValue = Base64.getEncoder().encodeToString(blobData); // Encode the byte array as Base64
    } else {
    columnValue = null; // If blob data is null
    }
    } else {
    // Handle other column types
    columnValue = resultSet.getObject(i);
    }

    record.put(columnLabel, columnValue);
    }
    results.add(record);
    }

    resultSet.close();
    } catch (SQLException e) {
    return Map.of("error", "unable to process request");
    }

    return Map.of("records", results);
    }





    Below is the code in flutter that I use to get the data from the server and to download the file.

    code::



    static Future<void> download_form_attachment(String attachment_id) async {
    print("Starting download for attachment_id: $attachment_id");


    List<Map<String, dynamic>> attachment_datas = globalProviderContainer.read(form_page_provider.notifier).state.sys_attachment_data.where((element) => element['sys_attachment_id'] == attachment_id).toList();

    Map<String, dynamic> attachment = globalProviderContainer.read(form_page_provider.notifier).state.sys_attachment.firstWhere((element) => element['sys_id'] == attachment_id);
    attachment_datas.sort((a, b) => a['sys_order'].compareTo(b['sys_order']));

    if (attachment_datas.isEmpty) {

    }

    print("Attachment type: ${attachment['sys_type']}");
    print("Attachment name: ${attachment['sys_name']}");
    String joined_data = attachment_datas.map((data) => data['sys_data']).join();
    print("joined_data (Base64 encoded): ${joined_data}");

    // Decode the base64 encoded data
    List<int> bytes = base64Decode(joined_data);
    String rawString = String.fromCharCodes(bytes);

    print("Decoded bytes: ${bytes}");

    try {
    if (attachment['sys_type'] == 'json') {
    // Convert bytes to string
    print("Raw string: $rawString");

    // Extract the actual byte values
    RegExp regex = RegExp(r'\[([^\]]+)\]');
    Match? match = regex.firstMatch(rawString);

    if (match != null) {
    String byteString = match.group(1)!;
    List<int> actualBytes = byteString.split(', ').map(int.parse).toList();

    // Convert actual bytes to string
    String jsonString = String.fromCharCodes(actualBytes);
    print("JSON string: $jsonString");

    // Parse the JSON string
    dynamic jsonData = json.decode(jsonString);
    // print("Parsed JSON data: $jsonData");

    final blob = html.Blob([jsonData], 'application/json');

    // Set the correct file name using sys_name from the attachment
    String fileName = '${attachment['sys_name']}';
    print("file_name: ${fileName}");

    // Create a download link
    final url = html.Url.createObjectUrlFromBlob(blob);
    final anchor = html.AnchorElement(href: url)
    ..setAttribute('download', fileName)
    ..click(); // Trigger the download

    // Clean up the URL after the download
    html.Url.revokeObjectUrl(url);
    } else {
    print("Failed to extract byte values from the string");
    }
    } else if (attachment['sys_type'] == 'pdf') {
    // Convert the bytes to a Blob
    final blob = html.Blob([bytes], 'application/pdf');

    // Set the correct file name using sys_name from the attachment
    String fileName = '${attachment['sys_name']}';
    print("file_name: ${fileName}");

    // Create a download link
    final url = html.Url.createObjectUrlFromBlob(blob);
    final anchor = html.AnchorElement(href: url)
    ..setAttribute('download', fileName)
    ..click(); // Trigger the download

    // Clean up the URL after the download
    html.Url.revokeObjectUrl(url);
    } else {
    print("Unhandled file type: ${attachment['sys_type']}");
    }
    } catch (e) {
    print("Error during file processing: $e");
    }
    }





    This is the output I see::

    try to download
    Starting download for attachment_id: 7dab2151-a826-46c4-b3c2-2ef843112f65_1728001280274
    No attachment data found, fetching from database
    Attachment type: pdf
    Attachment name: sample_pdf.pdf
    joined_data (Base64 encoded): KDExNzAyKVszNywgODAsIDY4LCA3MCwgNDUsIDQ5LCA0NiwgNTIsIDEwLCAzNywgMjExLCAyMzUsIDIzMywgMjI1LCAxMCwgNDksIDMyLCA0OCwgMzIsIDExMSwgLi4uXQ==
    Decoded bytes: [40, 49, 49, 55, 48, 50, 41, 91, 51, 55, 44, 32, 56, 48, 44, 32, 54, 56, 44, 32, 55, 48, 44, 32, 52, 53, 44, 32, 52, 57, 44, 32, 52, 54, 44, 32, 53, 50, 44, 32, 49, 48, 44, 32, 51, 55, 44, 32, 50, 49, 49, 44, 32, 50, 51, 53, 44, 32, 50, 51, 51, 44, 32, 50, 50, 53, 44, 32, 49, 48, 44, 32, 52, 57, 44, 32, 51, 50, 44, 32, 52, 56, 44, 32, 51, 50, 44, 32, 49, 49, 49, 44, 32, 46, 46, 46, 93]
    file_name: sample_pdf.pdf


    The pdf downloads but when I open the pdf I see this::

    [​IMG]

    I didnt see any stackoverflows that were exactly what I was looking for.

    [​IMG]

    [​IMG]

    Continue reading...

Compartilhe esta Página