用multi_image_picker http抖动上传图像

时间:2020-09-08 15:22:09

标签: flutter http flutter-dependencies

我有这段代码试图上传带有抖动的图像 该代码成功地从图库中选取了多个图像并显示,但无法成功上传 这是

“未处理的异常:错误状态:无法设置内容类型为“ multipart / form-data”的请求的正文字段。“

  List<Asset> images = List<Asset>();
  String _error = 'No Error Dectected';

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }




  Future<void> uploadAssets() async {

    List<MultipartFile> multipart = List<MultipartFile>();

    for (int i = 0; i < images.length; i++) {
      var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
      multipart.add(await MultipartFile.fromPath("file",path,filename: basename(path)));
    }
//    new http.MultipartFile('file', stream, length,
//        filename: basename(imageFile.path));
//    List<ByteData> byteDataList = await Future.wait(images.map((Asset image) => image.getByteData()));
//
//    List<Uint8List> byteArrayList = byteDataList.map((ByteData byteData) {
//      ByteBuffer byteBuffer = byteData.buffer;
//      return byteBuffer.asUint8List(byteData.offsetInBytes, byteBuffer.lengthInBytes);
//    }).toList();


//    Map data = {
//       : multipart,
//      'description' : 'here',
//      'size': '7899'
//
//    };

    var res = await httpSend(multipart);
    print(res);
  }
  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
 if (!mounted) return;

    setState(() {
      images = resultList;
      _error = error;
    });
  }




return new Scaffold(
      body: new Container(
            child:Container(

        child: Stack(
              children: [

 Visibility(

    visible:_pickvisiblee,
    child: Container(

    padding: EdgeInsets.fromLTRB(20.0,180.0,0.0, 0.0),
//    child: Stack(
    child:Column(
      children: <Widget>[
        Center(child: Text('Error: $_error')),
        RaisedButton(
          child: Text("Pick images"),
          onPressed: loadAssets,
        ),
        RaisedButton(
          child: Text("upload"),
          onPressed: uploadAssets,
        ),
        Expanded(
          child: buildGridView(),
        )
      ],
    ),
    ),
    ),


   ],
      ),
      );


    });
  }
}

我正在尝试使用http上传多个图像


Future httpSend(List<http.MultipartFile> params) async
{
  Map data ={
    'file':params
  };
  String endpoint = 'https://dynamicurl.com/api/uploadimage';
  final response= await http.post(endpoint, body: data,
    headers:{ "Content-Type":"multipart/form-data" } );
  List<dynamic> convertedDatatoJson = null;
  if(response.body.isEmpty){

    convertedDatatoJson =  null;
  }else{
    print(response.body);
    convertedDatatoJson =  jsonDecode(response.body);
  }
  return convertedDatatoJson;
}


这是错误 未处理的异常:错误状态:无法设置内容类型为“ multipart / form-data”的请求的正文字段。 我希望看到有关如何上传多张图像的解决方案,首先,将List转换为List,该错误是我工作的结果。

1 个答案:

答案 0 :(得分:1)

您可以使用 images_picker 和 Dio

link in pub dev IMAGES_PICKER

link in pub dev DIO

创建获取图像列表的方法

Future<List<Media>> getListImage() async {
return await ImagesPicker.pick(
  count: 3,
  pickType: PickType.image,
); }

并创建上传文件的方法

Future<void> uploadFile(String filePath) async {
    var filename = filePath.split("/").last;

    var formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(filePath, filename: filename)
    });

    Dio dio = new Dio();
    var response = await dio.post(YOUR_URL, data: formData);

    print(response);
  }

获取媒体列表并上传

var list = await getListImage();
    
list.forEach((element) async {
    
   await uploadFile(element.path);
    
});