adamlofts/mysql1_dart

How to read and save a picture as MediumBob datatype on Mysql server

JP3871 opened this issue · 2 comments

Hi,

Does anybody already maked a example on how to read and load a mediumblob datatype on Mysql ?
I have a table Item with a mediumblob which contains the photo.

Thanks for your help

Future _getDirPath() async {
final Directory? dir = await getExternalStorageDirectory();
return dir!.path;
}

Below my code :

Future _writeData(Uint8List dataWrite, String extFile) async {
final _dirPath = await _getDirPath();

final _myFile = File(_dirPath + '/photo' + extFile);
// If file doesn't exist, it will be created automatically

Blob myPhoto = (await _myFile.writeAsBytes(dataWrite)) as Blob;

return _dirPath + '/photo' + extFile;
}

String sql =
"select pj_contenu,pj_extension FROM pj WHERE pj_type=1 and id_item='" +
idItem.toString() +
"'";

var resFetch = await conn.query(sql);
var resSQL = resFetch.toList();

Uint8List myImage = resSQL[0].elementAt(0).toString() as Uint8List;
String extFile = resSQL[0].elementAt(1).toString();

String pathFile = await _writeData(myImage, extFile);

The solution :

Future _getDirPath() async {
final Directory? dir = await getExternalStorageDirectory();
// le ! si null
return dir!.path;
}

Future _writeData(Blob dataWrite, String extFile) async {
final _dirPath = await _getDirPath();

final _myFile = File(_dirPath + '/photo' + extFile);
// If file doesn't exist, it will be created automatically

Uint8List image = Uint8List.fromList(dataWrite.toBytes());
await _myFile.writeAsBytes(image);

return _dirPath + '/photo' + extFile;
}

for (var row in resFetch) {
  Blob myImage = row[0];
  extFile = row[1];
  pathFile = await _writeData(myImage, extFile);
}

@JP3871

Got stuck in same issue
I am downloading image from url than sending it to mysql but for me its not working

var imgResp=await http.get(Uri.parse(finalImgLink));

        Blob blob=Blob.fromString(imgResp.body);
        String q="INSERT INTO table (library_id,img_bin) VALUES ($lastId,'${blob}')";