Flutter DIO: upload image using binary body with Dio package Flutter DIO: upload image using binary body with Dio package dart dart

Flutter DIO: upload image using binary body with Dio package


Just putting my solution if someone stumbles upon the same issue.

I had to upload the file at a signed google storage URL. API required to insert the file binary data in the body of the PUT request. Couldn't implement using the DIO plugin, I resolved the issue using the DART HTTP package, Below is a sample code.

import 'package:http/http.dart' as http;await http.put(  Uri.parse(uploadURL),  headers: {    'Content-Type': mimeType,    'Accept': "*/*",    'Content-Length': File(filePath).lengthSync().toString(),    'Connection': 'keep-alive',  },  body: File(filePath).readAsBytesSync(),);


I also faced the same you have. In DIO you have to send the binary data through streams. Here is the example how I achieved it,

Uint8List image = File(path).readAsBytesSync();Options options = Options(  contentType: lookupMimeType(path),  headers: {    'Accept': "*/*",    'Content-Length': image.length,    'Connection': 'keep-alive',    'User-Agent': 'ClinicPlush'  });Response response = await dio.put(  url,  data: Stream.fromIterable(image.map((e) => [e])),  options: options);


I have declared a FormData object named 'data' and have a map of image with key as filename and value as filepath. 'image' is the key defined on the server side.

 data.files.add(MapEntry(    'image',      await MultipartFile.fromFile(image.values.first, filename: "${image.values.first.split("/").last}")                                ));