Base 64 convert to Image and get the error Invalid character (at character 6) - flutter

I am still struggiling with this annoying error. I have base64 string which I want to convert to Image. Here is the simpliest piece of code which is doing exactly what I want (at least, I saw it in different answers and code samples on the SO). I am getting the error:
Invalid character (at character 6)
my code is:
final String encodedStr = 'https://securelink.com/cameratypes/picture/13/true';
Uint8List bytes = base64.decode(encodedStr);
and i want to disply image:
Image.memory(bytes)

Finally, I found the solution, I don't know if it is important and will be useful to anyone who is struggling like me, but I am going to help. So, it would be easy and quick because I have already converted my image to nedeed formart (my image is base64 format), i made a dumb mistake when I was trying to convert it in String again, because it is already a String and I need Uint8List format. Side note: if your api devs said it should take a cookie or any kind of auth, it should be so.
code:
Future<String> _createFileFromString() async {
final response = await http.get(
Uri.parse(
'your link here',
),
headers: {
'cookie':
'your cookie here'
});
final Uint8List bytes = response.bodyBytes;
String dir = (await getApplicationDocumentsDirectory()).path;
String fullPath = '$dir/abc.png';
print("local file full path ${fullPath}");
File file = File(fullPath);
await file.writeAsBytes(List.from(bytes));
print(file.path);
final result = await ImageGallerySaver.saveImage(bytes);
print(result);
return file.path;
}
This code saves your image in straight to the app gallery and do not display on the screen anything

If your URI that contains data after comma as it is defined by RFC-2397. Dart's Uri class is based on RFC-3986, so you can't use it. Split the string by comma and take the last part of it:
String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);
REFERENCE: https://stackoverflow.com/a/59015116/12382178

Related

Upload Blob Url to Firebase Storage | Flutter

So I already read about the topic but I simply didn't understand the solutions on stack.
I came up with this code:
Im saving a url looking like this:
final String myDataUrl = file.url;
print(myDataUrl);
blob:http://localhost:51947/2952a3b1-db6a-4882-a42a-8e1bf0a0ad73
& then Im trying to add it into Firebase Storage with the putString operator, that I guessed that suited me best while reading the Documentation. I thought that I have a Url and therefore should be able to upload it like this:
FirebaseStorage.instance
.ref()
.child("bla")
.putString(myDataUrl, format: PutStringFormat.dataUrl);
But it doesn't work, it says that:
Error: Invalid argument (uri): Scheme must be 'data': Instance of '_Uri'
So Im guessing that it somehow can't format my url to one that is accepted.
What can I do different to upload a blob successfully to firebase Storage?
-----------------Answer----------------------
Answer in the comment of the answer.
You have to convert your Blob to a Uint8List & upload it like:
Future<Uint8List> fileConverter() async {
final reader = html.FileReader();
reader.readAsArrayBuffer(file!);
await reader.onLoad.first;
return reader.result as Uint8List;
}
and then put it into your Storage:
Future uploadFile(String uid) async {
if (file == null) return;
final path = "nachweise/$uid";
Uint8List fileConverted = await fileConverter();
try {
FirebaseStorage.instance
.ref()
.child(path)
.putData(fileConverted)
.then((bla) => print("sucess"));
} on FirebaseException catch (e) {
return null;
}
}
The Firebase Storage SDKs can upload local data as either a File, an array of bytes, or a base-64 encoded string. The only URLs it accepts are so-called data URLs, which start with data:// and contain the complete data of the object. They cannot upload data directly from URLs that you more commonly see, such as http:// or https://.
You'll need to first download the data from that URL to the local device, and then upload it from there.

Upload CSV file Flutter Web

I am using the file_picker plugin to pick a CSV file in Flutter Web. Although I am able to pick the file it is converting the file into bytes (Uint8List). Is there any way I can get the original CSV file or if I can convert these bytes to CSV maybe I can get the path of the file?
Code:
void pickCSV() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['csv']);
if (result != null) {
var fileBytes = result.files.first.bytes;
csfFileName.value = result.files.first.name;
} else {
// User canceled the picker
}
}
I know it's a bit late but you have a couple of choices and maybe it helps others out aswell.
Both of the choices requires server-side processing, so you will need to read on how to do that.
Get the content of the CSV file send it to the server and make a new file on the server with that content. You can use String.fromCharCodes to read the content, in the web, after you select the file.
Convert the Uint8List into a base64 string, using base64Encode function, send it to the server, process it there.
Alternatively, if you use Firebase Storage you can use putData like so:
final metaData = SettableMetadata(contentType: mimeType);
final task = await _storage.ref().child(cloudPath).putData(fileData, metaData);
/// Get the URL
await task.ref.getDownloadURL()
Storing the mimeType ensures proper handling of the file when used after download
cloudPath means the location in FirebaseStorage, such as: storageDirectory/filename.extension
fileData is the Uint8List you provided

How to retrieve/decode json/map from downloaded ByteStream?

I have a ByteStream downloaded from a Server, namely datas regarding the user.
Its in MySql server as
"username":"Neor","totalCoins":"350"
The truncated part of .php file that gives-away this data, is as follows:
$data = $stmt->fetchColumn();
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".strlen($data));
echo $data;
I use ths Flutter code to download the data:
Future<void> downloadData() async {
var url = Uri.parse("https://example.com/mycloud.php");
var request = http.MultipartRequest('POST', url)
..fields["user"] = "Dia";
var response = await request.send();
var stream = response.stream; }
On checking if the downloaded ByteStream contains anything, I've used print(stream.length), which prints out as 137.
How can I get the information I want from the ByteStream?
(If my question lacks in any way, please let me know.)
There shouldn't be any need to use a multipart request for a simple POST. Instead use the simpler http.post method.
Future<void> downloadData() async {
final response = await http.post(
Uri.parse('https://example.com/mycloud.php'),
body: <String, String>{
'user': 'Dia',
},
);
final decodedJson = json.decode(response.body);
// if you want to ensure the character set used, replace this with:
// json.decode(utf8.decode(response.bodyBytes));
}
If you do stick with the stream way, you have a Stream<List<int>> that you want to turn initially into a List<int>. Use the toList() method on stream for that. Then you have to decode that into characters. JSON is always encoded in utf8, so you could:
json.decode(utf8.decode(await stream.toList()));
(Under the hood, http is basically doing that for you; collecting the stream together and doing the character decoding and presenting that as body.)
First
import 'dart:convert' show utf8;
String foo = utf8.decode(bytes);
Then
Map valueMap = json.decode(foo );

GDrive api: Whenever the file name contains special utf-8 chars -> "Content size exceeds specified contentLength. [...]" [duplicate]

This question already has answers here:
Flutter: HttpClient post contentLength -- exception
(3 answers)
Closed 2 years ago.
I'm writing a flutter application, in which I want to sync files to Google Drive. However I came across the problem, that whenever I want to upload a file for which I specify the name with a utf-8 char. like e.g. in "Käsekuchen", I get the following exception:
"ClientException (Content size exceeds specified contentLength. 1410067 bytes written while expected 1410066. [--314159265358979323846--])":
When I change the name to something without the special character, it works fine. I guess the solution is quite simple but I couldn't find it.
import 'package:googleapis/drive/v3.dart' as ga;
var client = GoogleHttpClient(await googleSignInAccount.authHeaders);
var drive = ga.DriveApi(client);
ga.File fileToUpload = ga.File();
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = "Käsekuchen.jpg";
var response = await drive.files.create(
fileToUpload,
uploadMedia:
ga.Media(uploadFile.openRead(), uploadFile.lengthSync()),
);
So do I have to specify a certain encoding somewhere or what am I doing wrong?
Answer:
The special character is endoded as two bytes. You need to account for this in the content length.
Fix:
Change:
var response = await drive.files.create(
fileToUpload,
uploadMedia:
ga.Media(uploadFile.openRead(), uploadFile.lengthSync()),
);
to:
var response = await drive.files.create(
fileToUpload,
uploadMedia:
ga.Media(uploadFile.openRead(), uploadFile.lengthSync() + 1),
);

Special characters not working in Firestore string

I'm trying to pull some data from a website to my Firebase Firestore database, but I got a small problem with special characters being converted to weird characters, for example this phrase "he’s good at – finding people." is converted to this one "he’s good at – finding people.", do I have to escape those characters or what?
Code:
String url =
'some-url';
var response = await http.get(url);
String body = response.body;
List results = jsonDecode(body)['results'];
await firestore
.collection('games')
.document(results[i]['id'].toString())
.setData({
'description': results[i]['description']});
just used utf8 to decode the result string,
utf8.decode(results[i]['description'].toString().runes.toList());
Thanks for help.