简体   繁体   English

Flutter 多部分图像不与正文的 rest 一起发送

[英]Flutter multipart image no sending with the rest of the body

I'm trying to send a multipart request using the flutter http package and so far, every field is sent successfully, except the image.我正在尝试使用 flutter http package 发送多部分请求,到目前为止,每个字段都已成功发送,图像除外。 The code is below.代码如下。

Future multipartPostRequestProfile(
      id, dob, country, state, gender, File? imgPath) async {
    var token = await storage.read(key: 'jwt');
    var request = http.MultipartRequest(
        'PUT', Uri.parse('url'));

    request.files.add(await http.MultipartFile.fromPath(
      "image",
      imgPath!.path,
    ));
    request.fields['dateOfBirth'] = dob;
    request.fields['country'] = country;
    request.fields['state'] = state;
    request.fields['gender'] = gender;

    request.headers.addAll({
      "Content-Type": "multipart/form-data",
      "Authorization": "Bearer $token"
    });
    var res = await request.send();
    var result = await http.Response.fromStream(res);

    if (result.statusCode != 200)
      return {'result': result.statusCode, 'body': result.body};
    final Map<String, dynamic> responseData = jsonDecode(result.body);
    return responseData;
  }

try this..method试试这个..方法

Future multipartRequestPost(
String url,
String methodName, {
required Map<String, String> header,
File? image1,
File? image2,
Map<String, String>? body,
String? image1Key,
String? image2Key,
  }) async {
    var client = http.Client();
    try {
     String fullURL = APIUrl.baseUrl + url;
     var request = http.MultipartRequest(methodName, 
   Uri.parse(fullURL));
  if (body != null) {
    request.fields.addAll(body);
  }
  if (image1?.path.isNotEmpty ?? false) {
    request.files.add(await http.MultipartFile.fromPath(image1Key ?? '', 
    image1?.path ?? ''));
      request.files.add(await http.MultipartFile.fromPath(image2Key ?? 
     '', image2?.path ?? ''));
    }
  request.headers.addAll(header);
  http.StreamedResponse response = await request.send();
  final respStr = await response.stream.bytesToString();
  if (response.statusCode == 200 || response.statusCode == 201) {
    return response.statusCode;
  } 
} 
catch (exception) {
  client.close();
  throw AppException.exceptionHandler(exception);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM