简体   繁体   English

使用 dart HTTP POST 一个 python 文件

[英]HTTP POST a python file using dart

I want to send a python file via http post in dart.我想通过 dart 中的 http post 发送一个 python 文件。 I can do it in CURL the following way:我可以通过以下方式在 CURL 中做到这一点:

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:我也可以像这样在 python 中做到这一点:

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.由于 CURL 和 python,我知道服务器正在工作。 How do I mimic the functionality in CURL/python using dart?如何使用 dart 模拟 CURL/python 中的功能?

I was able to send the python file via a POST using dio .我能够使用dio通过 POST 发送 python 文件。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM