Thứ Ba, 22 tháng 12, 2020

Dart Base64Utils

 import 'dart:convert';

import 'dart:io';
import 'dart:typed_data';

class Base64Utils {
///Create one function and pass file path, It will return Bytes.
static Future<Uint8List> _readFileByte(String filePath) async {
Uri myUri = Uri.parse(filePath);
File audioFile = new File.fromUri(myUri);
Uint8List bytes;
await audioFile.readAsBytes().then((value) {
bytes = Uint8List.fromList(value);
print('reading of bytes is completed');
}).catchError((onError) {
print('Exception Error while reading audio from path:' +
onError.toString());
});
return bytes;
}

///get base64 string from full filePath

static Future<String> getBase64String(String filePath) async {
try {
Uint8List fileBytes = await _readFileByte(filePath);
String base64String = base64.encode(fileBytes);
return base64String;

// _readFileByte(filePath).then((bytesData) {
// Uint8List fileBytes = bytesData;
//
// ///do your task here
// print('DO TASK');
// print('--DO TASK:'+filePath);
// String base64String = base64.encode(fileBytes);
// print(base64String);
// return base64String;
// });
} catch (e) {
// if path invalid or not able to read
print(e);
}
return '';
}

static Future<String> getBase64StringFromByteData(ByteData byteData) async {
try {
Uint8List fileBytes = byteData.buffer.asUint8List();
String base64String = base64.encode(fileBytes);
return base64String;
} catch (e) {
// if path invalid or not able to read
print(e);
}
return '';
}

/// base64 encode and decode string
static String encode(String str) {
var bytes = utf8.encode(str);
return base64.encode(bytes);
}

static String decode(String encodedString) {
var data = base64.decode(encodedString);
return utf8.decode(data);
}
}

Không có nhận xét nào:

Đăng nhận xét