qing
qing

Reputation: 885

How to post asset image to server using MultipartFile in 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?

Upvotes: 1

Views: 4564

Answers (1)

Richard Heap
Richard Heap

Reputation: 51750

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

Upvotes: 3

Related Questions