如何在Flutter App中将图像上传到服务器并解码服务器的json响应?

时间:2019-10-11 08:46:25

标签: flutter dart

我的服务器上有一个端点,该端点接受multipart / form-data并发回json作为响应。 我想将Flutter应用中的图片发送到服务器,并解码从服务器接收到的json。

1 个答案:

答案 0 :(得分:0)

您可以为此使用http.MultipartRequest

示例:-

  static Future<UploadImageRes> uploadImage(int id, File imageFile) async {
    if (imageFile != null) {
      var stream = new http.ByteStream(imageFile.openRead());
      var length = await imageFile.length();
      String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);
      var uri = Uri.parse(UrlConstants.ADD_RECIPE_PHOTO);

      LogUtils.d("====uri :   $uri");
      LogUtils.d("====recipeId :   $id");

      var request = new http.MultipartRequest("POST", uri);
      String fileName = imageFile.path.split("/").last;
      var multipartFile = new http.MultipartFile('photo', stream, length,
          filename: fileName, contentType: new MediaType('image', 'jpeg'));

      request.headers.addAll({"Authorization": "Bearer $token"});
      request.files.add(multipartFile);
      request.fields["recipeId"] = "$id";

      var response = await request.send();
      var statusCode = response.statusCode;

      LogUtils.d("====statusCode :   $statusCode");

      if (statusCode < 200 || statusCode >= 400) {
        throw new ApiException("Uploading failed");
      }

      final respStr = await response.stream.bytesToString();
      return Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr)));

    } else {

      throw new ApiException("Uploading failed");

    }

  }

final respStr = await response.stream.bytesToString();中,您将获得api响应