0

I want to send a python file via http post in dart. I can do it in CURL the following way:

curl -X POST -F 'file=@/home/user/file.py' http://192.168.80.1:9888/dir/file.py

I am also able to do it in python like this:

import requests

url = 'http://192.168.80.1:9888/dir/file.py'
files = {'file': open('file.py', 'rb')}
print(files)
r = requests.post(url, files=files)

But in dart I am not able to send the post. I have tried several methods but is at this on currently:

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

void main(List<String> arguments) async {
  var response;
  var file;
  var url = 'http://192.168.80.1:9888/dir/file.py';
  file = File('file.py').readAsStringSync();
  var files = {'file': file};
  response = await http.post(url, body: files);
}

Which result in the following exception: Exception has occurred.

ClientException (Connection closed before full header was received)

I know that the server is working due to CURL and python. How do I mimic the functionality in CURL/python using dart?

Daniel
  • 546
  • 6
  • 17

1 Answers1

0

I was able to send the python file via a POST using dio.

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

Future<dio.FormData> FormData3() async {
  return dio.FormData.fromMap({
    'file': await dio.MultipartFile.fromFile(
      'files/file.py',
      filename: 'file.py',
    ),
  });
}

Future<dio.Response> sendFile() async {
  dio.Response response;

  response = await dio.Dio().post('http://192.168.80.1:9888/dir/file.py',
      data: await FormData2(), onSendProgress: (received, total) {
    if (total != -1) {
      print((received / total * 100).toStringAsFixed(0) + '%');
    }
  },
      options: dio.Options(
        method: 'POST',
        responseType: dio.ResponseType.plain,
      ));
  return response;
}

void main() async {
  response = await sendFile();
}
Daniel
  • 546
  • 6
  • 17