Home > Net >  Send picture to server api with post request [FLUTTER]
Send picture to server api with post request [FLUTTER]

Time:11-14

I want to take picture, which should contain just a few letters, with my phone and then send it to a server where it will convert the picture to a text string.

My imported packages:

import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

I currently have this camera function:

// Camera implementation
  File? _image;
  final ImagePicker _picker = ImagePicker();

  Future getImage() async {
    final image = await _picker.pickImage(source: ImageSource.camera);
    setState(() {
      _image = File(image!.path);
    });
  }

And I use it in this button:

// Camera button
ElevatedButton.icon(
   onPressed: getImage,
   icon: const Icon(Icons.camera_alt_rounded),
   label: const Text('Scan'),
   style: ButtonStyle(
     backgroundColor: MaterialStateProperty.all(Colors.green[500]),
     textStyle: MaterialStateProperty.all(const TextStyle(fontSize: 26)),
   )
)

I have tested to just send some data to jsonplaceholder and it works, but I can't get understand how to implement it to a picture that should be sent to my server.

// Send Data to the Server (TEST VERSION)
postDataTest() async{
  try{
  var response = await http.post(Uri.parse("https://jsonplaceholder.typicode.com/posts"),
      body: {
        "id": 1.toString(),
        "name": "Hax",
      }
  );
  print(response.body);
  } catch(e){
    print(e);
  }
}

TLDR. I want to take a picture and send it to a server.

CodePudding user response:

Use multipart

Upload(File img) async {    

  var uri = Uri.parse(uploadURL);

 var request = new http.MultipartRequest("POST", uri);
  request.files.add( new http.MultipartFile.fromBytes("file", img.readAsBytesSync(), filename: "Photo.jpg", contentType: new MediaType("image", "jpg"))); 
      


  var response = await request.send();
  print(response.statusCode);
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}

CodePudding user response:

Picture to text for archive this you need to convert image into base64. Check this link

However, it's generally a bad idea to store large blobs of binary data in your database. you will end up wasting bandwidth transmitting data.it also decrease mobile app performance while you read large blob data. you don't need as well as unnecessary encoding and decoding.

You can send picture to server using multipart api request.

So you can archive mutipart request with api in various packages

  1. https - dart documentation
  2. Dio

You can also check multipartRequest on Stackoverflow.

  • Related