Flutter esys_flutter_share and image picker saver not working - flutter

I am trying to download an image and the save image. It’s downloading the image but it’s not opening the share. What am I missing here. I am using this package esys_flutter_share 1.0.2
and image_picker_saver 0.3.0
void onImageDownLoad(Product product, isLoading) async {
final String text = "${product.name}\n\n${product.description}";
var request = await HttpClient().getUrl(Uri.parse(product.image));
var response = await request.close();
isLoading = true;
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
var filepath = await ImagePickerSaver.saveFile(fileData: bytes);
final ByteData newBytes = await rootBundle.load(filepath);
isLoading = false;
await Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg',
text: text);
}

So finally figured it out imagePicker saver is a future and need to be completed before the share is called.So I added whenComplete.
void onImageDownLoad(Product product, isLoading) async {
isLoading = true;
final String text = "${product.name}\n\n${product.description}";
var req = await HttpClient().getUrl(Uri.parse(product.image));
var response = await req.close();
isLoading = false;
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await ImagePickerSaver.saveFile(fileData: bytes).whenComplete(() {
EsysShare.Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg',
text: text);
});
}

Related

Image URL from firebase storage to firestore

this is how I upload images to firebase storage and get the Download URL in firebase Firestore. Everything works properly how ever I get the 1st URL but not the Second one.
Future<void> uploadImage2(image2) async {
setState(() {
isLoader2 = true;
});
final bytess = image2.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp/2.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl2 = (await task);
String url = (await downloadUrl2.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl2 = url;
setState(() {
isLoader2 = false;
});
}
Future<void> uploadImage3(image3) async {
setState(() {
isLoader3 = true;
});
final bytess = image3.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl3 = (await task);
String url = (await downloadUrl3.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl3 = url;
setState(() {
isLoader3 = false;
});
}
You can upload image to firebase as below
First of all you need to add this plugin in pubspec.yaml
firebase_storage: ^8.0.0
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> uploadFile(File _image) async {
setState(() {
isLoader = true;
});
final bytess = _image.readAsBytesSync(); //"_image" is your selected image or any other which you need to upload
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'image/jpeg');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('cover_photo/'+timeStamp.toString()+'insp_cover_photo.png').putData(bytess,metadata);
firebase_storage.TaskSnapshot downloadUrl = (await task);
String url = (await downloadUrl.ref.getDownloadURL()); //this is the url of uploaded image
setState(() {
isLoader = false;
});
}
Let me know if you have any questions
You can do it using firebase_storage.
you can get url by using this function.
Future<String> uploadFile(File _imageFile) async {
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
Reference reference = FirebaseStorage.instance.ref().child(fileName);
UploadTask uploadTask = reference.putFile(_imageFile);
return uploadTask.then((TaskSnapshot storageTaskSnapshot) {
return storageTaskSnapshot.ref.getDownloadURL();
}, onError: (e) {
throw Exception(e.toString());
});
}

Print QR code using esc_pos_printer flutter

I'm using esc_pos_printer package which can print a receipt over network. I need two features
Save a qr/bar code in the gallery
Print said qr/bar code using the thermal printer/regular printer
For saving the qr code I did:
static Future<File> _saveBarCode(GlobalKey key, String productId) async {
print("save bar code");
RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "/" + productId + ".png";
File imgFile = File(path);
print(imgFile.path);
return imgFile.writeAsBytes(pngBytes);
}
and
static void save(GlobalKey key, String productId) async {
_saveBarCode(key, productId).then((value) async {
bool? saved = await GallerySaver.saveImage(value.path);
print("saved: $saved");
}).catchError((error) {
print(error);
});
}
But the printing part is giving me trouble:
void printOverNetwork(GlobalKey key, String productId) async {
const PaperSize paperSize = PaperSize.mm80;
final profile = await CapabilityProfile.load();
final printer = NetworkPrinter(paperSize, profile);
final PosPrintResult result =
await printer.connect('192.168.0.123', port: 9100);
_saveBarCode(key, productId).then((value) {
if (result == PosPrintResult.success) {
// print the qr/barcode
}
});
}
How can I solve the issue?

Flutter 'File' can't be assigned to 'XFile'

I have a function to save network image to local cache files, but I have a trouble when store the list file that I downloaded to List<XFile>. Here is my download function:
List<XFile>? imageFileList = [];
Future<File> downloadImage(url, filename) async {
var httpClient = HttpClient();
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
final dir = await getTemporaryDirectory();
File file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes);
print('downloaded file path = ${file.path}');
return file;
} catch (error) {
print('download error');
return File('');
}
}
is there any way so I can save the file to imageFileList as :
imageFileList!.add(file);
Convert the file to XFile:
XFile file = new XFile(file.path);
Change your list type:
from this:
List<XFile>? imageFileList = [];
to this:
List<File>? imageFileList = [];
final ImagePicker _picker = ImagePicker();
getImage() async {
var images = await _picker.pickMultiImage();
images!.forEach((image) {
setState(() {
_imageFileList!.add(File(image.path));
});
});
}

Upload Image Flutter Storage

i am use 'image_picker_web/image_picker_web.dart' in my app. Now when I choosed image, this image displayed, it's work. But when i try to save image in storage nothing happens.
Uint8List _image1;
Future getImg() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
// debugPrint(tempImg.toString());
_image1 = tempImg;
});
}}
save in storage:
void uploadImg() async {
final StorageReference productImg =
FirebaseStorage.instance.ref().child('ProductImg');
var timekey = DateTime.now();
final StorageUploadTask uploadTask =
productImg.child(timekey.toString() + 'jpg').putData(_image1);
var imageUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
url = imageUrl.toString();
print('Image Url' + url);}
button:
RaisedButton(
onPressed: () {
uploadImg();
}
what am I doing wrong?
Give this a try:
final file = File.fromRawPath(uint8list);
final ref = FirebaseStorage.instance.ref().child("users/some_id/ProductImg.jpg");
final task = ref.putFile(file, StorageMetadata(contentType: "image/png"));
final snapshot = await task.onComplete;
if (snapshot.error != null) throw snapshot.error;
final downloadURL = await snapshot.ref.getDownloadURL();

how to upload image to rest API in flutter through http post method?

I'm trying to upload an image through the flutter via post method. and I'm using image_picker for pick file from mobile but I can't able to upload
and I have tried to send the file like FormData that also doesn't work
Future<dynamic> uploadLicence(int id ,dynamic obj) async {
FormData formdata = new FormData(); // just like JS
formdata.add("image",obj);
final response = await post('Logistic/driver/LicenceImage?
driverId=$id',
formdata);
print(response);
// return null;
if (response.statusCode == 200) {
final result = json.decode(response.body);
return result;
} else {
return null;
}
}
after that, I just tried with this method but this also not working
Future<dynamic> uploadLicence(int id, File file) async {
final url = Uri.parse('$BASE_URL/Logistic/driver/LicenceImage?
driverId=$id');
final fileName = path.basename(file.path);
final bytes = await compute(compress, file.readAsBytesSync());
var request = http.MultipartRequest('POST', url)
..files.add(new http.MultipartFile.fromBytes(
'image',bytes,filename: fileName,);
var response = await request.send();
var decoded = await
response.stream.bytesToString().then(json.decode);
if (response.statusCode == HttpStatus.OK) {
print("image uploded $decoded");
} else {
print("image uplod failed ");
}
}
List<int> compress(List<int> bytes) {
var image = img.decodeImage(bytes);
var resize = img.copyResize(image);
return img.encodePng(resize, level: 1);
}
It's possible with MultipartRequest. Or you can use simply dio package. It's one command.
With http:
import 'package:http/http.dart' as http;
final Uri uri = Uri.parse(url);
final http.MultipartRequest request = http.MultipartRequest("POST", uri);
// Additional key-values here
request.fields['sample'] = variable;
// Adding the file, field is the key for file and file is the value
request.files.add(http.MultipartFile.fromBytes(
field, await file.readAsBytes(), filename: filename);
// progress track of uploading process
final http.StreamedResponse response = await request.send();
print('statusCode => ${response.statusCode}');
// checking response data
Map<String, dynamic> data;
await for (String s in response.stream.transform(utf8.decoder)) {
data = jsonDecode(s);
print('data: $data');
}
I user this code for my project i hope work for you
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}