【问题标题】:Flutter : Multipart File request not workingFlutter:多部分文件请求不起作用
【发布时间】:2021-04-01 22:45:28
【问题描述】:

我想通过多部分文件请求上传图片。使用此代码当我传递两个图像文件时,它工作正常。但是当我想传递一个图像文件而另一个为空时,它就不起作用了。 问题出在哪里?我该如何解决这个问题?

这是我的代码 -

Future<Map<String, dynamic>> updateprofile(
      UpdateProfileInfo updateProfileInfo,
      File imageFile,
      File signatureFile) async {

    String url = "$baseAPIUrl/update-profile-info";
    String _token = await SavedData().loadToken();
    String authorization = "Bearer $_token";

    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Authorization": authorization
    };

    var request = http.MultipartRequest("POST", Uri.parse(url));

    request.headers.addAll(headers);
    request.fields.addAll(updateProfileInfo.toJson());

    request.files
        .add(await http.MultipartFile.fromPath('image', imageFile.path));
    request.files.add(
        await http.MultipartFile.fromPath('signature', signatureFile.path));

    print(" Update Profile Json ${updateProfileInfo.toJson()}");
    print("Request Fields ${request.fields}");
    http.StreamedResponse response = await request.send();

    String respStr = await response.stream.bytesToString();
    dynamic respJson;

    try {
      respJson = jsonDecode(respStr);
    } on FormatException catch (e) {
      print(e.toString());
    }

    print('API ${response.statusCode}\n  $respJson');

    bool isSuccess = response.statusCode == 200;
    var data = json.decode(respStr);

    return {
      'isSuccess': isSuccess,
      "message": isSuccess ? data["success"]["message"] : null,
      "name": isSuccess ? data["success"]["name"] : null,
      "classgroup": isSuccess ? data["success"]["classgroup"] : null,
      "image": isSuccess ? data["success"]["image"] : null,
      "error": isSuccess ? null : data['error']['message'],
    };
  }

这里是邮递员截图

1.

2。 POSTMAN 为 Dart 生成的代码 - http

【问题讨论】:

  • 你怎么知道 " ...它不起作用。"?
  • 表示您想在一个参数中为单个请求传递多个图像对吗?
  • @ShubhamNarkhede 抱歉,没有一个参数。我传递了两个参数 File imageFile 和 File signatureFile
  • @pskink 看到我的输出,好像是这样,我的 API 没有命中

标签: api flutter http multipart


【解决方案1】:

当您的文件之一为空时,您应避免将其添加到请求正文中。

if(imageFile != null){
    request.files
        .add(await http.MultipartFile.fromPath('image', imageFile.path));
}
if(signatureFile != null){
request.files.add(
        await http.MultipartFile.fromPath('signature', signatureFile.path));
}

因为signatureFile.path 会在这里导致错误

【讨论】:

  • 不工作。收到错误“未处理的异常:FileSystemException:无法检索文件的长度,路径='文件:'/data/user/0/com.tcs.tryon_v5/cache/image_picker3432035215283692220.jpg''(操作系统错误:没有这样的文件或目录, errno = 2)"
【解决方案2】:

使用 dio 包应该可以工作

   Future<bool> updateImage(var pickedFile) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();` <br/>
    var token = sharedPreferences.getString("token");
    Dio dio = Dio(); 
    final File file = File(pickedFile.path);
   String fileName = file.path.split('/').last;
   dio.options.headers["authorization"] = token;
   FormData formData = FormData.fromMap({
     "image": await MultipartFile.fromFile(file.path),
     });
    try {
     var response = await dio.post(API.kBASE_URL, data: formData);
           if (response.statusCode == 200) {
           return true;
           } else {
                   return false;
                 }
          } catch (r) {
                        return false;
                       }
     }

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 2014-03-02
    • 2019-10-06
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多