Home > Enterprise >  Flutter/Dart: How upload binary file to Dropbox?
Flutter/Dart: How upload binary file to Dropbox?

Time:04-24

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?

CodePudding user response:

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.

CodePudding user response:

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);
  • Related