'Flutter/Dart: How upload binary file to Dropbox?

I'm trying to upload a binary file to Dropbox using https://github.com/dart-lang/http. Following https://dropbox.github.io/dropbox-api-v2-explorer/#files_upload, my code is:

import 'package:http/http.dart' as http;

Map<String,String> headers = {
  'Authorization': 'Bearer MY_TOKEN',
  'Content-type': 'application/octet-stream',
  'Dropbox-API-Arg': '{"path": "/file", "mode": "overwrite"}',
};

final resp = await http.post(
    Uri.parse("https://content.dropboxapi.com/2/files/upload"),
    body: "--data-binary @\'/my/binary/file\'",
    headers: headers);

file gets uploaded, but unfortunately this only contains the text --data-binary @'/my/binary/file' (i.e. not the actual file).

Am I missing something/doing something incorrectly?



Solution 1:[1]

Sending binary data directly as the body worked:

import 'package:http/http.dart' as http;

final file = File('/my/binary/file');
Uint8List data = await file.readAsBytes();

Map<String,String> headers = {
    'Authorization': 'Bearer MY_TOKEN',
    'Content-type': 'application/octet-stream',
    'Dropbox-API-Arg': '{"path": "/file", "mode": "overwrite"}',
};

final resp = await http.post(
    Uri.parse("https://content.dropboxapi.com/2/files/upload"),
    body: data,
    headers: headers);

Solution 2:[2]

Since you pass

body: "--data-binary @\'/my/binary/file\'",

as the body of your POST request, exactly this is the data to get send to the server. The body is raw data, that just gets passed along to the server and in no way interpreted by dart.

Have a look at Dart's MultipartRequest. Or for general information:SO on multipart requests.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andyandy
Solution 2 SteAp