Невозможно загрузить PDF-файл из MariaDB с помощью FlutterJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Невозможно загрузить PDF-файл из MariaDB с помощью Flutter

Сообщение Anonymous »

У меня возникли трудности с загрузкой PDF-файла из mariadb.
Я могу загрузить файл json без каких-либо проблем.
Это то, что я вижу в базе данных Mariadb. Я храню данные вложений в длинном объекте.

Код: Выделить всё

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, ...] |
+---------------------------------------------------------------------------------------------------+

Я думаю, что храню массив байтов, но не знаю, почему перед данными стоят (16) и (11702).
по какой-то причине мое приложение не любит загружать длинные объекты, поэтому мне пришлось изменить метод на моем сервере, чтобы получить данные из базы данных.
это метод, который извлекает данные из базы данных::

Код: Выделить всё

public static Map get_records(String query_string) {
List 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 record = new HashMap();
for (int i = 1; i  element['sys_attachment_id'] == attachment_id).toList();

Map 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  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 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");
}
}

Вот что я вижу:

Код: Выделить всё

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
PDF-файл загружается, но когда я открываю его, я вижу следующее:
[img]https:// i.sstatic.net/Ixa2HFxW.png[/img]

Я не увидел ни одного переполнения стека, которое было бы именно тем, что я искал.
Изображение

Изображение


Подробнее здесь: https://stackoverflow.com/questions/790 ... ng-flutter
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»