upload multi Image Picker with dio (package is out of date) problem - flutter

I used to upload Images with this code below but due to package update it doesn't work anymore I read the documentation but it didn't work and I didn't know how to use multipart
here is the code
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:dio/dio.dart';
Future getImage() async {
files.clear();
List<Asset> resultList = List<Asset>();
resultList = await MultiImagePicker.pickImages(
maxImages: 2,
enableCamera: false,
);
for (var asset in resultList) {
int MAX_WIDTH = 500; //keep ratio
int height = ((500 * asset.originalHeight) / asset.originalWidth).round();
ByteData byteData =
await asset.requestThumbnail(MAX_WIDTH, height, quality: 80);
if (byteData != null) {
List<int> imageData = byteData.buffer.asUint8List();
UploadFileInfo u = UploadFileInfo.fromBytes(imageData, asset.name);
files.add(u);
}
}
setState(() {
_isUploading = true;
});
}
List<UploadFileInfo> files = new List<UploadFileInfo>();
Future<List<String>> uploadImage() async {
FormData formData = new FormData.from({"files": files});
Dio dio = new Dio();
var response =
await dio.post("http://localhost:3004/upload", data: formData);
UploadImage image = UploadImage.fromJson(response.data);
return image.images;
}
the errors are in the following lines
UploadFileInfo u = UploadFileInfo.fromBytes(imageData,asset.name);
List<UploadFileInfo> files = new List<UploadFileInfo>();
FormData formData = new FormData.from({"files": files});
so what do I need to change to make it work and what is the multipart ??
Any help will be appreciated
Thanks in advance

if (images.isEmpty || images[0] != null) {
for (int i = 0; i < images.length; i++) {
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
http.MultipartFile multipartFile =
http.MultipartFile.fromBytes('image', imageData,
filename: images[i].name,
contentType: MediaType('image', 'jpg'));
imagestoEdit.add(multipartFile);
print(imagestoEdit.length);
}
}
Dio.post(url,formdata:{images:imagestoEdit})

Related

How can I upload mutiple-photo in flutter app via ImgePicker

I want to add the function which can upload multiple Photo image via ImagePicker
In this code, I can just upload single photo, not mutiple.
This app operating by flutter, dart and firebase server.
[Code]
void dispose() {
textEditingController.dispose();
super.dispose();
}
File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1000,
maxHeight: 1000,
);
setState(() {
_image = image;
});
}
Future _uploadFile(BuildContext context) async {
if (_image != null) {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().millisecondsSinceEpoch}.png');
final task = firebaseStorageRef.putFile(
_image,
StorageMetadata(contentType: 'image/png'),
);
final storageTaskSnapshot = await task.onComplete;
final downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
}
final images = await _picker.pickMultiImage(
maxHeight: 1024,
maxWidth: 1024,
imageQuality: 50,
);
I created here 3 functions used to pick files from imagePicker and to upload them to firebase storage.
first, pick images from gallery:
final imageFiles = await pickImages();
second, upload the images:
final path = 'path/where/you/want/to/save/your/images';
final imageUrls = uploadImages(imagesFiles, path)
print(imageUrls);
you can now use the images urls to save to firestore
Future<List<File>> pickeImages() async {
ImagePicker picker = ImagePicker();
final images = await picker.pickMultiImage(
maxHeight: 1000, maxWidth: 1000, imageQuality: 90);
List<File> files = [];
if (images == null || images.isEmpty) return [];
for (var i = 0; i < images.length; i++) {
final file = File(images[i].path);
files.add(file);
}
return files;
}
Future<String?> _uploadImageFile(File file, String path) async {
try {
final storage = FirebaseStorage.instance;
TaskSnapshot? taskSnapshot;
final storageRef = storage.ref().child(path);
final uploadTask = storageRef.putFile(file);
taskSnapshot = await uploadTask.whenComplete(() {});
final imageUrl = await taskSnapshot.ref.getDownloadURL();
return imageUrl;
} catch (e) {
throw Exception(e.toString());
}
}
Future<List<String>> uploadImages(
List<File> files,
String path,
) async {
final urls = <String>[];
try {
if (files.isNotEmpty) {
for (var i = 0; i < files.length; i++) {
final file = files[i];
final imagePath = '$path/${Random().nextInt(10000)}.jpg';
final url = await _uploadImageFile(file, imagePath);
urls.add(url!);
}
}
return urls;
} on FirebaseException {
rethrow;
}
}
Instead of using ImagePicker.pickImage, use ImagePicker.pickMultiImage. That gives you a List instead of an XFile. Then you can just upload all images in the list. For instance, add an image parameter to your _uploadFile Function so that its function signature is
Future _uploadFile(BuildContext context, XFile image)
and just upload all images like
for (final image of images) {
_uploadFile(context, image)
}

How to parse a binary data collection (list of files) from multipart/form-data http response?

How to parse a multipart/form-data of http response from server, if it contains a list of binary files (images)?
For example:
var request = http.MultipartRequest('GET', url);
var streamedResponse = await request.send();
if (streamedResponse.statusCode == 200) {
var response = await http.Response.fromStream(streamedResponse); // it is just a binary data, not a list of files
}
Maybe there is something similar to HttpMultipartParser from .NET in flutter?
Try below solution
Future uploadmultipleimage(List images) async {
var uri = Uri.parse("");
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers[''] = '';
request.fields['user_id'] = '10';
request.fields['post_details'] = 'dfsfdsfsd';
//multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
List<MultipartFile> newList = new List<MultipartFile>();
for (int i = 0; i < images.length; i++) {
File imageFile = File(images[i].toString());
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var multipartFile = new http.MultipartFile("imagefile", stream, length,
filename: basename(imageFile.path));
newList.add(multipartFile);
}
request.files.addAll(newList);
var response = await request.send();
if (response.statusCode == 200) {
print("Image Uploaded");
} else {
print("Upload Failed");
}
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

Flutter esys_flutter_share and image picker saver not working

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);
});
}

How can i post image with dio in flutter

i want to send image to server by jpg format by dio package ,
how can i do this ?
choose image method :
void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
file = file;
print(file);
});
upload image method :
void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
"image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
print(json.decode(onValue));
});
Anyone help me ?
thanks
Please try this
Future<dynamic> _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
"image": await MultipartFile.fromFile(file.path,filename: fileName),
};
return await Dio()
.post(url,data:formData).
then((dynamic result){
print(result.toString());
});
}
You can also use http for this purpose
Future<String> uploadImage(Asset asset,String orderId) async {
// String to uri
Uri uri = Uri.parse('Your URL');
// create multipart request
http.MultipartRequest request = http.MultipartRequest("POST", uri);
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
http.MultipartFile multipartFile = http.MultipartFile.fromBytes(
'image',
imageData,
filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
contentType: MediaType("image", "jpg"),
);
// Add field to your request
request.fields['FieldName'] = fieldValue;
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
// Decode response
final respStr = await response.stream.bytesToString();
return respStr;
}

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);
});
}