Flutter Retrofit上传文件

aym*_*der 3 dart retrofit flutter

我正在使用 flutter Retrofit 包,尝试将数据上传到服务器(Laravel)。基本上,文件应作为 MultiPart 部分注释发送。另外,我应该与文件(在我的例子中是图片)一起发送不同的值,所以我使用了@Part()map<String,dynamic>。

这是我的代码

@POST('register')
  Future<RegisterResponse> register(@Body() Map<String, dynamic> body, @Part() File pic);
Run Code Online (Sandbox Code Playgroud)

这是我的要求

Map<String, dynamic> body = {
                            "name":" widget.fullName",
                            "username": "widget.userName",
                            "phone": "698281556",
                            "country_code": "+213",
                            "email": "widget.email@gmail.com",
                            "birth_date": "18-09-2021",
                            "pic": imageFile,
                            "lat": 36.347285,
                            "lon": 6.603381,
                            "address": "widget.userName",
                            "city": "widget.userName",
                            "residential": "widget.userName",
                            "device_token": "widget.userName",
                            "code": "123456",
                            "tags": [1,2]
                          };

                          final logger = Logger();
                          final dio = Dio(); // Provide a dio instance
                          dio.options.headers["Content-Type"] =
                          "multipart/form-data";
                          dio.options.headers["X-Requested-With"] =
                          "XMLHttpRequest";
                          final client = RestClient(dio);

                          client.register(body,imageFile!).then((it) async {

                            print(it.access_token);

                          }).catchError((Object obj) {

                            // non-200 error goes here.
                            switch (obj.runtimeType) {
                              case DioError:
                              // Here's the sample to get the failed response error code and message
                                final res = (obj as DioError).response;
                                logger.e(
                                    "Got error : ${res!.statusCode} -> ${res.data}");
                                break;
                              default:
                            }
                          });
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它不起作用。没有足够的文档来说明这一点。谢谢你的帮助

Xol*_*awn 17

不幸的是文档没有提到这一点。
您必须使用注释您的请求@Multipart才能上传文件。

另一种必须注意的情况是,当您使用 注释您的请求时@Multipart,您必须使用 注释所有字段@Part。即使那些不是文件的。

一个例子:

  @POST('/store')
  @MultiPart()
  Future<dynamic> store({
    @Part() required String title,
    @Part() required int part,
    @Part() File? attach,
  });
Run Code Online (Sandbox Code Playgroud)

  • @AbdulmalekDery你是对的,虽然这个问题应该像[这里](https://github.com/trevorwang/retrofit.dart/pull/158)那样解决,但我认为使用`MultipartFile`作为[这个答案] (/sf/answers/5234181221/)最好避免这种情况。 (3认同)