flutter post 向服务器请求文件

flutter post request to server with file

亲爱的,我是 flutter 的新手,我想从 flutter 向服务器发送 post 请求 这是 post 人工请求

Image-Post-Request

Post header:

key Value

Accept: application/json

Content-Type: application/x-www-form-urlencoded

Post 身份验证:

Bear Token

Post Body:

key : Value

address : address

description: description

feedback: feedback

media: download.png

我想从 flutter 中提出这个请求 这是我的代码:

File _img; // taken by camera

Map<String,String> headers = {
        'Content-Type':'application/json',
        'Authorization': 'Bearer $token',
      };

 final msg = jsonEncode({
        "address"    : _address,
        "description": _description,
        "feedback"   : _techicalSupport,
        "media"      : _img;
       });


 try{
        var response = await http.post(
          "url",
          headers: headers,
          body: msg,
        );
        print("${response.toString()}");
   }catch(e){
        print("${e.toString()}");
    }

我收到这个错误: 未处理的异常:将 object 转换为可编码的 object 失败:“_File”实例

注意媒体不是必需的,当我从body中删除它时它可以工作并在数据库中创建记录

我想在 body 中包含媒体。 请问我该怎么做...

您应该使用 MultipartRequest 发送文件。

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';

void send() async {
  final msg = {
    "address": "test",
    "description": "test",
    "feedback": "test",
  };

  File _img;

  var image = await ImagePicker.pickImage(source: ImageSource.camera);

  _img = image;

  var response = await http.MultipartRequest(
      'POST', Uri.parse("url"))
    ..fields.addAll(msg)
    ..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
        contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));


  print(response);
}

您需要将 _img 转换为 MultipartFile

    MultipartFile file=MultipartFile.fromBytes(
        'media', await filePath.readAsBytes(),
        filename: 'FILE_NAME');

    var request = http.MultipartRequest("POST", Uri.parse(url));
    if (files != null) request.files.add(file);

1.Configure FilePicker 库(可选步骤,您可以 select 您的文件使用任何库)

然后选择文件

File file = await FilePicker.getFile();

2.Configure dio library , versions here

import 'package:dio/dio.dart';

然后

FormData formData = FormData.fromMap({
 "FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
              });

    var response = await Dio().post("FULL_URL_HERE", data: formData);

    print(response);

这是我的问题的答案,我使用了 Dio 库:

  import 'package:dio/dio.dart';

    File myImage;
    List<File> _images = [];


    // to handle image and make list of images
    _handleImage()async{
        File imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
        if(imageFile != null){
            myImage = imageFile;
            _images.add(imageFile);
        }
      }



    // for post data with images
    void _submit() async{ 
        FormData formData = FormData();

        _images.forEach((image) async{
              formData.files.addAll(
                  [
                    MapEntry(
                      "media[]",
                      await dio.MultipartFile.fromFile(image.path),
                    ),
                  ]
              );
        });

        formData.fields.add(MapEntry("address", _address),);
        formData.fields.add(MapEntry("description", _description),);
        formData.fields.add(MapEntry("feedback", _techicalSupport),);

        var response = await new Dio().post(
            postUrl,
            options: Options(
              headers: {
                "Content-Type": "application/json",
                "Authorization" : 'Bearer $token',
              }
            ),
            data: formData
         );

        print("${response.toString()}");
    }