How to post asset image to server using MultipartFile in flutter - flutter

I am using MultipartFile to send my image file to server. I know that when I use ImagePicker
File ImageFile;
_openCamera() async {
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
this.setState(() {
imageFile = picture;
});
}
then use MultipartFile like this
request.files.add(http.MultipartFile.fromBytes('img', ImageFile.readAsBytesSync(), filename: 'photo.jpg'));
But my problem is I want my image is from my assets like from here Image.asset('images/photo1.png');. I have error
A value of type 'Image' can't be assigned to a variable of type 'File'.
Try changing the type of the variable, or casting the right-hand type to 'File'.
So, my question is how I can send my image using MultipartFile method?

First, obtain the asset as list of bytes:
var bytes = (await rootBundle.load('images/photo1.png')).buffer.asUint8List();
Then use that in the MultipartFile named constructor:
var mpFile = http.MultipartFile.fromBytes('img', bytes, filename: 'photo.jpg');

Related

while uploading image to firebase, this one error is always comes whatever i do

what went wrong? even if i replace the XFile into File, same error comes at this putFile.
try this convert that xfile to file
uploadImages(XFile? pathsw) async {
final paths = path.basename(pathsw!.path);
final pathStorage =
"${NAMEFOLDER}/${PATHNAME}/$paths";
/// Start looking from here then so on
final file = File(pathsw.path);
final reference = FirestoreService.storage.ref().child(pathStorage);
final task = reference.putFile(file);
final snap = await task.whenComplete(() {});
final url = await snap.ref.getDownloadURL();
return url;
}
If you see, .putFile() takes in a element of File type. And you're accepting of type XFile. To convert:
File uploadImage = File(image!.path)
now the best way to upload would be to use .putFile() or .putData()
Your .putFile() implementation looks great, if you want to use .putData(), find the following code:
await reference.putData(uploadImage.readAsBytesSync())

Store image uploaded by user into Flutter Web as an actual .jpg file

I am using the flutter_web_image_picker package to allow the user to select -and then upload to Firebase- an image.
However, the package returns an image widget, which I can display, but I cannot upload to Firebase. Therefore, I am trying to read the package's code and update it to fit my needs.
In general, I think the packages main functionalities are:
It gets the file
//...
final reader = html.FileReader();
reader.readAsDataUrl(input.files[0]);
await reader.onLoad.first;
final encoded = reader.result as String;
Then it 'strippes' it
final stripped = encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');
final imageName = input.files?.first?.name;
//...
To finally return it as a Widget:
final imageName = imageName;
final imageData = base64.decode(stripped);
return Image.memory(imageData, semanticLabel: imageName);
As I said, it works perfectly, however, I need to adapt it to my needs:
I would like to get the image as a .jpg file so that I can upload it to Firebase.
Is any of the variables above the actual .jpg file? Is there any transformation that I should perform to get a .jpg file?
Thanks!
I based my answer on this post.
Basically, on the flutter_web_image_picker package, before the code I posted, there were a few lines that get an actual html file:
final html.FileUploadInputElement input = html.FileUploadInputElement();
input..accept = 'image/*';
input.click();
await input.onChange.first;
if (input.files.isEmpty) return null;
Then using firebase's pacakge, I uploaded the image as follow:
import 'package:firebase/firebase.dart' as fb;
fb.StorageReference storageRef = fb.storage().ref('myLocation/filename.jpg');
fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(input.files[0]).future;
Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
return imageUri;

Converting Image FlutterWebImagePicker Output to File

I'm using Flutter web for a webapp and having trouble converting an image from the image picker to a file in order to upload it to my server. I display the image in Image.file(xxx) but I get the error:
Error while trying to load an asset: FormatException: Illegal scheme
character (at character 6)
Image(image:%20MemoryImage(Uint8List%234267a,%20scale:%201),%20frameBuilder...
Here is the code I'm trying:
Future getImage(bool isCamera) async {
Image image;
if (isCamera) {
image = await FlutterWebImagePicker.getImage;
} else {
}
var bytes = await rootBundle.load('$image');
String tempPath = (await getTemporaryDirectory()).path;
File file = File('$tempPath/profile.png');
await file.writeAsBytes(
bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
setState(() {
currentSelfie = file;
_accDetails['customer_selfie'] = currentSelfie;
});
}
Thanks in advance
I've tested this package and was very happy with the result imagePickerWebit returns 3 different types it can be in the form of Image(widget for preview), byte, File(upload)
then you can use this to get the values
html.File _cloudFile;
var _fileBytes;
Image _imageWidget;
Future<void> getMultipleImageInfos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
if (mediaFile != null) {
setState(() {
_cloudFile = mediaFile;
_fileBytes = mediaData.data;
_imageWidget = Image.memory(mediaData.data);
});
}
I havent used the plugin although your code has 2 issues. One is the if statement and the second one is using Rootbundle. If you are picking from the filesystem, my assumption isCamera would be false. You have not added any logic for the falsy condition.
if (isCamera) {// This would be true if the source was camera
image = await FlutterWebImagePicker.getImage;
} else {
}
Additionally,
var bytes = await rootBundle.load('$image');
From the flutter documentation, rootbundle contains the resources that were packaged with the application when it was built. Those are assets that you define in your pubspec. yaml. You are selecting an image at runtime hence its not bundled as an asset.
Since the package appears to return an image object, use the toByteData method on the image i.e
image = await FlutterWebImagePicker.getImage;
await image.toByteData();//This method has some parameters. Look into them

Flutter: Convert Base64 String image url to File and use it in FileImage or related widgets

I've tried this way, and use it in FileImage but haven't found a rally point
Uint8List bytes = base64.decode(imageBase64);
File file = File.fromRawPath(bytes);
imageBase64 is the image url that has been encode.
The point of this thing is, i want to use it in FileImage or another widget image file but i don't want this image is saved to device and upload this file to the attachments file Rest API
can anyone help me.
If what you want to do once you have the bytes is to show the image, then you can use Image.memory.
var imageWidget = Image.memory(bytes);
OTOH If you're trying to upload the image, you don't need to convert it into file. You can use bytes directly assuming you can't upload it using base64 enconding. Package http
import 'package:http/http.dart';
...
//create multipart using filepath, string or bytes
MultipartFile multipartFile = MultipartFile.fromBytes(
'file',
byteData,
filename: fileName,
);
//add multipart to request
request.files.add(multipartFile);
var response = await request.send();
If you have an UintList8 you can use MemoryImage(bytes).
Uint8List bytes = base64.decode(imageBase64);
Image(image: MemoryImage(bytes));

How I can convert an image from gallery or camera to binary string?

I used image_picker to choose an image from gallery or take a photo with camera and now I have to send it on request to backend as an array of bytes. My issue is that I don't know How I can encode the image. Can anyone tell me what I should use and how?
var image = await ImagePicker.pickImage(source: ImageSource.camera);
File imageFile=image ;
List<int> imageBytes = imageFile.readAsBytesSync();
String base64Image = base64UrlEncode(imageBytes);