使用 post 请求 [FLUTTER] 将图片发送到服务器 api

Send picture to server api with post request [FLUTTER]

我想用我的 phone 拍照,照片应该只包含几个字母,然后将其发送到服务器,服务器会将照片转换为文本字符串。

我导入的包:

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

我目前有这个相机功能:

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

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

我在这个按钮中使用了它:

// 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)),
   )
)

我已经测试过只发送一些数据到 jsonplaceholder 并且它有效,但我不明白如何将它实现到应该发送到我的服务器的图片。

// 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。我要拍照发到服务器

使用多部分

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

Picture to text 要存档,您需要将图像转换为 base64。检查这个

但是,在数据库中存储大量二进制数据通常不是一个好主意。您最终会浪费带宽传输 data.it 并且在读取大型 blob 数据时还会降低移动应用程序的性能。你不需要也不需要不必要的编码和解码。

您可以使用多部分 api 请求将图片发送到服务器。

因此您可以在各种包中使用 api 归档多部分请求

  1. https - dart documentation
  2. Dio

您还可以在 Whosebug 上查看 multipartRequest

我设法用这个函数解决了它:

// Upload camera photo to server
Future uploadImage() async {
  final uri = Uri.parse("url to the server");
  var request = http.MultipartRequest('POST', uri);
  var takenPicture = await http.MultipartFile.fromPath("image", _image!.path);
  request.files.add(takenPicture);

  var response = await request.send();
  if(response.statusCode == 200){
    print('Image uploaded!');
  } else{
    print('Image not uploaded');
  }
}