如何将多个图像上传到服务器-Flutter

时间:2020-10-13 10:16:17

标签: json flutter dart

我目前正在通过使用 multi_image_picker:^ 4.7.14 并尝试在 dio:^ 3.0.10 < / strong> MultipartRequest。

尝试两次进行

void uploadProduct() async {
    var uri = Uri.parse(Constant.postAdUrl);
    Map<String, String> headers = {'Content-Type' : 'application/json'};
    http.MultipartRequest request = new http.MultipartRequest('POST', uri);
    request.headers.addAll(headers);
    request.fields['adcover'] = coverImage;
    request.fields['ads_userfkid'] = userId;
    request.fields['ads_name'] = widget.title;
    request.fields['ads_description'] = widget.description;
    request.fields['ads_price'] = widget.price;
    request.fields['ads_subcatfkid'] = widget.subId;
    request.fields['ads_location'] = widget.location;
    List<MultipartFile> newList = new List<MultipartFile>();
    for(int i=0; i<images.length; i++){
      File imageFile = File(images[i].toString());
      var stream = new http.ByteStream(imageFile.openRead());
      var length = await imageFile.length();
      var multipartFile = new http.MultipartFile('files[]', stream, length, filename:imageFile.path.split('/').last);
      newList.add(multipartFile);
    }
    request.files.addAll(newList);
    var response = await request.send();
    print(request.fields);
    if (response.statusCode == 200) {
      print(response);
      print("Image Uploaded");
    } else {
      print("Upload Failed");
    }
  }

这里出现错误,因为不能将参数类型MultipartFile(其中MultipartFile在http-0.12.2中定义)分配给参数类型MultipartFile(其中MultipartFile在dio-3.0中定义)。 10)

以另一种方式,我做到了

void uploadProduct() async {
    print("Inside conversion");
    String postUrl = Constant.postAdUrl;
    Map<String, String> headers = {'Content-Type' : 'application/json'};
    try {
      var dio = new Dio();
      FormData formData = new FormData.fromMap({
        'files[]' : images,
        'adcover' : _image,
        'ads_subcatfkid' : widget.subId,
        'ads_userfkid' : userId,
        'ads_name' : widget.title,
        'ads_description' : widget.description,
        'ads_price' : widget.price,
        'ads_location' : widget.location,
      });
      Response resp = await dio.post(postUrl, data: formData, options: Options(headers: headers));
      if(resp.statusCode == 200) {
        print(resp.data);
      }
    } catch(e){
      print(e);
    }
  }

但是这里没有任何数据被发布到服务器中

1 个答案:

答案 0 :(得分:0)

这是因为MultipartFiledio库中都存在http。除此行外,您已正确完成所有操作: List<MultipartFile> newList = new List<MultipartFile>(); 将此行更改为: List<http.MultipartFile> newList = new List<http.MultipartFile>(); 这应该工作。因为您必须导入了别名为http的{​​{1}}库。这就是为什么在任何地方都必须写httphttp.ClassName的原因。这也适用于http.FunctionName