retrofit.dart icon indicating copy to clipboard operation
retrofit.dart copied to clipboard

[ How to download a pdf|csv|xls file via retrofit ? ]

Open Gobmichet opened this issue 3 years ago • 2 comments

Hi, Just wondering how to download a file thanks to the lib ? I implemented the call with @GET and the interceptor tells me that : I/flutter (20751): [HEADER]content-disposition:[attachment; filename="report7678859861323098766.csv"] But it doesn't download it ! How to achieve this please ?

Gobmichet avatar Sep 26 '22 13:09 Gobmichet

please use dio download directly

trevorwang avatar Oct 03 '22 05:10 trevorwang

Hey @Gobmichet,

You can download files by receiving the data as bytes and then have a specific reader to read those bytes Like if you wanna download a PDF file, you do this:

@RestApi()
abstract class Api {
  factory Api(Dio dio, {String baseUrl}) = _Api;

  @GET('/your/api/path/to/that/pdf')
  @DioResponseType(ResponseType.bytes)
  Future<HttpResponse<List<int>>> getPDF(
    // Put your body, query parameters, or anything here
  );
}

And then, once you make the api call and receive the integer list data, convert them into Uint8List like so:

final dio = Dio();

// This api call may take some time if the PDF file is large
final bytes = await Api(dio).getPDF();

// Once the request goes successful, Convert it to Uint8List and use it to store it locally or
// read it through any PDF reader (most PDF readers support Uint8List data type)
final data = Uint8List.fromList(bytes.data);

Hope this helps you out, Please consider closing the issue if you found this solution is what you exactly need!

devmuaz avatar Feb 12 '23 17:02 devmuaz