genericUser
genericUser

Reputation: 7178

POST list of files using Retrofit

I'm using the retrofit package in order to generate HTTP requests within my app. I want to upload multiple files to our servers. The number of files is unknown (the list is dynamic).

I found a solution that describes how to upload one file using retrofit:

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

I'm looking to upload a list of files List<File>.

How do I achieve that?

Upvotes: 5

Views: 3783

Answers (1)

genericUser
genericUser

Reputation: 7178

Problem Solved.

I was able to send multiple files by adding the @MultiPart() annotation and sending the files as a List<MultipartFile>:

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

In order to convert List<File> to List<MultipartFile> I had to do the following:

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);
}

Upvotes: 14

Related Questions