Flutter dio如何上传图片

x4shl7ld  于 2023-04-22  发布在  Flutter
关注(0)|答案(2)|浏览(183)

我试图发送图像到机器学习模型与快速API它的工作与 Postman 罚款,但当我尝试与dio包它给我错误的类型是文件,我希望它是png或jpg与模型和api的工作
下面是选择图像的代码

import 'dart:io';

import 'package:breastcancer1/network/remote/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerPage extends StatefulWidget {
  const ImagePickerPage({Key? key}) : super(key: key);

  @override
  _ImagePickerPageState createState() => _ImagePickerPageState();
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  File? imageFile;

  final picker = ImagePicker();

  Future<void> _pickImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      imageFile = pickedFile != null ? File(pickedFile.path) : null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (imageFile != null) ...[
              Container(
                  height: 100, width: 100, child: Image.file(imageFile!)),
              const SizedBox(height: 20),
            ],
            ElevatedButton(
              onPressed: _pickImage,
              child: const Text('Select Image'),
            ),
            MaterialButton(
              onPressed: () {
                if (imageFile != null) {
                  print({"is it nulll        ${imageFile}"});
                  DioHelper.postImage(url: 'predict', query: {'image': imageFile}).then((value) {
                    print(value.data['class']);
                    print({"is it nosos nulll${imageFile.runtimeType}"});

                  }).catchError((error) {
                    print(error.toString());
                    print('why');
                  });
                } else {
                  print('No image selected');
                }
              },
              child: Text('press'),
            )
          ],
        ),
      ),
    );
  }
}

这是指令码

import 'package:dio/dio.dart';

class DioHelper{
  static Dio? dio;
  static init(){
    dio=Dio(
      BaseOptions(
        baseUrl: 'http://192.168.1.5:8000/',
        receiveDataWhenStatusError: true
      )
    );
  }

  static Future<Response> postImage({
    required String url,
    required Map<String,dynamic> query,
  })
  async
  {
    return await dio!.post( url, queryParameters: query, );
  }
}

这里是错误I/flutter(21041):DioError [bad response]:请求返回了无效的状态代码422。
我试着问聊天gpt,但仍然没有什么,它与 Postman 工作正常

vlju58qv

vlju58qv1#

static Future<Response> postImage({
    required File file,
    required String url,
    required Map<String, dynamic> query,
  }) async {
    String fileName = file.path.split('/').last;
    var fileExt = fileName.split('.').last;
    var formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        file.path,
        filename: fileName,
        contentType: MediaType("image", fileExt),
      ),
    });

    return await dio!.post(url, data: formData, queryParameters: query);
  }

通常,我们将文件作为表单数据发送,它支持二进制数据,允许在单个请求中传输多种数据类型,使用边界分离以便于解析,它受到广泛支持,并且是流友好的。
另外,我正在使用http_parser,它是dart.dev包,带有一个很好的帮助程序来创建MediaTypes。

dced5bon

dced5bon2#

MaterialButton(
              onPressed: () async{
                if ( PateintCubit.get(context).imageFile != null) {
                  FormData formData = FormData.fromMap({
                    'image': await MultipartFile.fromFile( PateintCubit.get(context).imageFile!.path),
                  });
                  print({"is it nulll        ${ PateintCubit.get(context).imageFile?.runtimeType}"});
                  DioHelper.postImage(url: 'predict', query: formData).then((value) {
                    print(value.data['class']);
                    print({"is it nosos nulll${ PateintCubit.get(context).imageFile.runtimeType}"});

                  }).catchError((error) {
                    print(error.toString());
                    print('why');
                  });
                } else {
                  print('No image selected');
                }
              },
              child: Text('press'),
            )

我是怎么解决的

相关问题