Upload image to server flutter (Image picker) - flutter

I want to upload an image to server
I'm using the Image Picker plugin to pick image
this code work without any exception on samsung tab
but Catch error on xiaomi phone.
the onImageButtonPressed run in all devices.
Future<void> onImageButtonPressed({
BuildContext? context,
}) async {
try {
final XFile? pickedFile =
await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
imageFileList!.add(pickedFile);
logger.i('done , image picked');
File image = File(pickedFile.path);
logger.i(image); // on xiaomi and samsung log the same result "File: '/data/user/0/com.grand.technology.driver/cache/8227d4f4-df70-441d-9677-b95b64b1bf323122241454085685040.jpg'"
await uploadOrderPic(order.id.toString(), image);
}
update();
} catch (e) {
pickImageError = e;
logger.e(e);
update();
}
}
but the exception happen here
uploadOrderPic(String id, File image) async {
uploading.value = true;
var response = await OrderApi()
.uploadOrderPic(orderID: id, image: image)
.then((value) {
logger.i(value.data); //samsung tab log Instance of 'UploadedImage' but xiaomi phone catch error
uploading.value = false;
var uploadedImage = (value.data) as UploadedImage;
imageURLsList.add(uploadedImage.url!);
}).catchError((error) {
Get.snackbar('Failed', 'Uploading Image Failed',
backgroundColor: redColor);
logger.e(error); // type 'Null' is not a subtype of type 'UploadedImage' in type cast
});
try {
} on TimeoutException {
Get.snackbar(
'Connection Error', 'Check Your Internet Connection Please!');
} catch (e) {
logger.e(e);
}
}
this code upload image to server
Future<ApiResponse> uploadOrderPic(
{required String orderID,
required File image}) async {
ApiResponse apiResponse = ApiResponse();
var token = await getToken();
try {
var request = http.MultipartRequest("POST", Uri.parse(uploadPicUrl));
request.files.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['id'] = orderID;
request.headers[HttpHeaders.authorizationHeader] = 'Bearer $token';
var response =
await request.send().then((value) => http.Response.fromStream(value));
apiResponse.data =
UploadedImage.fromJson(jsonDecode(response.body)['data']);
} catch (e) {
logger.e(e);
apiResponse.error = serverError;
}
return apiResponse;
}

Related

Connection closed before full header was received on http post in flutter

I'm trying to do a http post with the picture the user selects, when trying to make the http call, I get the error 'Connection closed before full header was received', I don't know how to fix it, the same error is happening on a real device.
This is also the documentation for the api, the body is form data.
class UploadVideoServices {
static Future<http.StreamedResponse> postProf({
required String imagePath,
required String title,
required bool isPayPerView,
required bool isDeleted,
required bool show,
required List<String> tags,
required String description,
}) async {
var headers = {'Authorization': 'Bearer ${prefs!.getString('token')}'};
var request = http.MultipartRequest(
'POST',
Uri.parse(
"http url/v1/postpic/634d0ebd2be78793c9474ae0/$title/$description/$show/$isPayPerView/$isDeleted/$tags"));
request.fields.addAll({
'file': imagePath,
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
return response;
}
}
=====
using the services
=====
postProf() async {
try {
var result = await UploadVideoServices.postProf(
imagePath: selectedImagePath.value,
title: 'ajanvideo',
isPayPerView: false,
isDeleted: false,
show: true,
tags: ['ajan', 'app'],
description: 'hey',
);
successSnackBar('Done', 'Posted prof');
return result;
} catch (e) {
errorSnackBar('Opps', e.toString());
print(e.toString());
}
}
======
void getImage(ImageSource imageSource) async {
try {
final pickedFile = await ImagePicker().pickImage(source: imageSource);
if (pickedFile != null) {
selectedImagePath.value = pickedFile.path;
}
print(selectedImagePath.value);
await postProf(); // using the method after getting image
} catch (e) {
errorSnackBar('Opps', 'Failed to get image');
}
}

I'm wrapping the firebase storage function that upload images with try catch but when i lost network an error occurs

here i'm wrapping the function with the catch error but still the error exists;
'W/NetworkRequest( 3326): error sending network request POST https://firebasestorage.googleapis.com' but the app didn't crash or something.
final profileImageUrl = await uploadImage(profileImage!, 'Profile Pictures')
.catchError((error) {
print(error);
});
Future<String> uploadImage(XFile image, String savedFolderName) async {
try {
storage_ref.Reference firebaseStorageReference =
storage_ref.FirebaseStorage.instance.ref().child(savedFolderName);
storage_ref.UploadTask uploadImage = firebaseStorageReference
.child('${DateTime.now()}')
.putFile(File(image.path));
storage_ref.TaskSnapshot taskSnapshot =
await uploadImage.whenComplete(() {});
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
return downloadUrl;
} catch (error) {
rethrow;
}
}

uploading multiple xfiles to firebase storage

I am trying to upload multiple (max 5) xfiles images (image_picker library) to firebase storage. currently, it uploads only one with the below method:
Future<void> addProduct({
BuildContext? ctx,
String? proName,
String? productDescription,
double? count,
double? price,
required List<XFile> images
}) async {
try {
var imageUrls = await Future.wait(images.map((_image) =>
uploadFile(_image)));
await firestore
.collection(outletsCollection)
.doc(_currentUserOutletId)
.set({
products: FieldValue.arrayUnion([
{
productId: Uuid().v4(),
productName: proName,
prodDesc: productDescription,
countInStock: count,
productPrice: price,
productImg: FieldValue.arrayUnion([imageUrls]),
}
]),
});
} catch (err) {
String errMsg = "error blahblah";
errorDialog(ctx!, errMsg);
}
notifyListeners();
}
for the uploadFile method i tried using images.forEach() instead of .map(), but it gave me void type error. uploadFile method:
Future<String> uploadFile(XFile _image) async {
var storageReference = storage
.ref()
.child('product_images')
.child(_currentUserOutletId!)
.child(Uuid().v4());
final metadata = SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'picked-file-path': _image.path},
);
if (kIsWeb) {
await storageReference.putData(await _image.readAsBytes(), metadata);
} else {
await storageReference.putFile(io.File(_image.path), metadata);
}
return await storageReference.getDownloadURL();
}
so, at the end only one image is uploaded and addProduct() does not add product to firestore database. log in android studio returns nothing. I couldn't find a method that would work with the xfile. help appreciated very much!
List<XFile> _imageFileList;
try{
final pickedFile = await _picker.pickMultiImage();
setState(() {
_imageFileList = pickedFile;
_imageFileList.forEach((element) async {
firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;
var date = DateTime.now().millisecondsSinceEpoch;
try {
setState(() {
_loading = true;
});
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance.ref('uploads/photos/'+date.toString()+'_image.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
await storage.ref('uploads/file-to-upload.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
firebase_storage.TaskSnapshot downloadUrl = (await task);
String url = (await downloadUrl.ref.getDownloadURL());
// print(url.toString());
} on FirebaseException catch (e) {
// e.g, e.code == 'canceled'
setState(() {
_loading = false;
});
}
});
try this way using image_picker plugin. You can get url after image upload and you have yo it in your data.

cannot able to send files with extact format in flutter

I'm currently working in a flutter, I'm trying to send a file to the backend server. But I can send a file but the extension is showing as BIN and the file is not supported.
pick() async {
var img = await ImagePicker().getImage(source: ImageSource.gallery);
image = img;
}
send() async {
// if (imageFile == null) {
// return Get.snackbar("alert", 'Please select image');
// }
try {
String? message = messageController.text;
final url = Uri.parse('http://localhost:8000/integration-test');
//Map<String, String> headers = {'Authorization': 'Bearer $token'};
Uint8List data = await this.image.readAsBytes();
List<int> list = data.cast();
var request = http.MultipartRequest('POST', url)
//..headers.addAll(headers)
..fields['sender'] = "venkat"
..fields['numbers'] = numbers
..fields['message'] = message;
if (image != null) {
request.files.add(http.MultipartFile.fromBytes('file', list,
filename: 'example.jpeg'));
}
var response = await request.send();
//var decoded = await response.stream.bytesToString().then(json.decode);
if (response.statusCode == 200) {
Get.snackbar("alert", 'SUCESS');
} else {
Get.snackbar("alert", 'FAILED');
}
} catch (e) {
Get.snackbar('alert', 'Image failed: $e');
}
}
and help to set the file name dynamically.
when i done it with ajax and jquery it works file i need the exact result like this
let formData = new FormData();
let file = $('#1file')[0].files[0];
const sender=c;
const message = $('.i-message').val();
const datepick=$("#i-datetimepicker").val();
formData.append('sender',c);
formData.append('numbers',JSON.stringify(irecepient));
formData.append('message',message);
if(file){
formData.append('file',file);
}
if(datepick){
formData.append('date',datepick);
}
$.ajax({
type: "POST",
url: "http://localhost:8000/integration-test",
//enctype: 'multipart/form-data',
contentType:false,
processData:false,
data: formData,
success: function (data) {
if(data !=0){
$('.logs').append($('<li>').text("task processing"));
}else{
$('.logs').append($('<li>').text("task failed"));
}
}
});
});
this works good and i expect the above flutter code to do this

Image upload using post method in Flutter

I have to upload image from gallery to server using provider in Flutter.
Here is the file picker
_loadPicker(ImageSource source) async {
File picked = await ImagePicker.pickImage(source: ImageSource.gallery);
print(picked);
if (picked != null) {
final response = await Provider.of<ProfilePictureUpdate>(context, listen:
false).profilePicUpdate(picked);
if (response["status"] ) {
Fluttertoast.showToast(msg: response["title"]);
}
else {
Fluttertoast.showToast(msg: response["title"]);
}
}
}
And here is the post method
Future<Map<String, dynamic>> profilePicUpdate(picked) async {
try {
final response = await ApiRequest.send(route: "profile/update/picture", method: "POST",
body: {
" photo_url" : picked,
});
if (response.statusCode == 200 ) {
return {
"status": true,
"title" : response["title"]
};
}
}
If you want sent image to you have to use formData( multi part) in 'Dio' similar
web (enctype). In http, you can also use multipart.
Must remember u use image is always not same, here use this field when server side params name same.
class ImageRepository {
Future<dynamic> uploadImage(filepath) async {
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(filepath,
filename: filepath.split('/').last)
});
var response = await Dio().post(
url,
data: formData),
);
print(response.data);
if (response.statusCode == 200) {
return 'Image Upload';
} else {
throw Exception 'Problem occour';
}
}