首页 > 解决方案 > Flutter:如何使用 formdata 和 multipartfile 上传多个资产?

问题描述

我仍在学习颤振,使用multi_image_picker,formdata和. 将资产上传到服务器时出现错误dio。如果没有图像,我可以成功上传,但null如果包含任何图像,我会收到错误消息。

请帮我。

此代码用于选择图像。

Future<void> loadAssets() async {
String error = 'No Error Detected';
try{
  resultList = await MultiImagePicker.pickImages(
    maxImages: 4,
    enableCamera: true,
    selectedAssets: images,
    cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
  );
} on Exception catch (e){
  error = e.toString();
}

if(!mounted) return;
setState((){
  images = resultList;
  error = error;
});
}

此代码用于将 formData 上传到服务器。

upload(List<Asset> imageList) async {

var formData = FormData.fromMap({
  "userId": _id,
  "post": _postContent,
  "tags": _tags.join(",").toString(),
});

if(null != imageList) {
  for (int i = 0; i < imageList.length; i++) {
    ByteData byteData = await imageList[i].getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    formData.files.addAll([
      MapEntry(
          "images[]",
            MultipartFile.fromBytes(
            imageData,
            filename: 'load_image',
            contentType: MediaType("image", "png"),
          )),
    ]);
  }

} 
  
  // this is where I pass the data to the server using dio
  AuthService().userForumPost(formData).then((val) async {
    print(val.data);
    print('Form Submitted Successfully');
    _confirmationDialog(context);
  });
}

标签: uploadmultipartform-dataassetsform-datadio

解决方案


推荐阅读