使用 Retrofit POST 文件列表

gen*_*ser 4 retrofit flutter

我正在使用改造包来在我的应用程序中生成 HTTP 请求。我想将多个文件上传到我们的服务器。文件数量未知(列表是动态的)。

我找到了一种解决方案,描述了如何使用改造上传一个文件:

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

我正在寻找上传文件列表List<File>

我该如何实现这一目标?

gen*_*ser 9

问题解决了。

我能够通过添加@MultiPart()注释并将文件作为以下格式发送来发送多个文件List<MultipartFile>

@POST('/your/api/url')
@MultiPart()
Future<List<S3FilesResponse>> uploadFilesToS3({
  @Part() required String folderName,
  @Part() required List<MultipartFile> files,
});
Run Code Online (Sandbox Code Playgroud)

为了转换List<File>List<MultipartFile>我必须执行以下操作:

final multipartFiles = <MultipartFile>[];

for (final file in files) {
  final fileBytes = await file.readAsBytes();
  final multipartFile = MultipartFile.fromBytes(
    fileBytes,
    filename: file.path.split('/').last,
    contentType: MediaType('application', 'octet-stream'),
  );
  multipartFiles.add(multipartFile);
}
Run Code Online (Sandbox Code Playgroud)