Use Flutter to send a http Post-Request (containing an image) to a Flask API
I have done similar work with Django and Flutter. I used image_picker to select image and used dio to upload image.
This is upload function:
_upLoadImage(File image) async { setState(() { loadingdone = false; }); String path = image.path; var name = path.substring(path.lastIndexOf("/") + 1, path.length); var suffix = name.substring(name.lastIndexOf(".") + 1, name.length); FormData formData = FormData.fromMap({ "img": await MultipartFile.fromFile(path,filename: name) }); Dio dio = new Dio(); var respone = await dio.post<String>("http://192.168.1.104:8000/uploadImg/", data: formData); if (respone.statusCode == 200) { Fluttertoast.showToast( msg: 'Done!', gravity: ToastGravity.BOTTOM, textColor: Colors.grey); setState(() { _label = jsonDecode(respone.data.toString())['label']; _score = jsonDecode(respone.data.toString())['score']; loadingdone = true; }); } }
Run upload function after select image:
Future getImage() async { var image = await ImagePicker.pickImage(source: ImageSource.gallery); _upLoadImage(image); setState(() { _image = image; }); }
You may already know how to choose an image from the gallery/camera (e.g. using image_picker
library). You fill a class field like File image;
with the result of that picker. This could be as easy as:
import 'dart:io';import 'package:image_picker/image_picker.dart';class _MyHomePageState extends State<MyHomePage> { File image; final picker = ImagePicker(); pickImageFromGallery(ImageSource source) async { final image = await picker.getImage(source: source); setState(() { this.image = File(image.path); }); }}
(Change the ImageSource source
to match your desire: camera or gallery)
Then you can upload that file to your api.Using http
library:
import 'package:http/http.dart' as http;import 'package:http_parser/http_parser.dart';class _MyHomePageState extends State<MyHomePage> {doUpload(){ var request = http.MultipartRequest( 'POST', Uri.parse("url_to_api"), ); Map<String, String> headers = {"Content-type": "multipart/form-data"}; request.files.add( http.MultipartFile( 'image', image.readAsBytes().asStream(), image.lengthSync(), filename: "filename", contentType: MediaType('image', 'jpeg'), ), ); request.headers.addAll(headers); print("request: " + request.toString()); request.send().then((value) => print(value.statusCode));}}
For each one of these libraries, you have to add them as dependency inside pubspec.yaml
in your flutter project:
cupertino_icons: ^0.1.3http: ^0.12.2image_picker: ^0.6.7