我在PHP中有一个代码如何在python cURL中做到这一点

时间:2019-05-29 09:54:45

标签: php python curl

我有问题,一个人有一个没有php的ubuntu服务器,这个人不想在该服务器上安装php,我需要使用cURL或python上传文件,但是我只知道如何在php中做到这一点,我没有使用python :(。的任何基本步骤。有人可以用php来帮助我完成我的代码。我尝试了类似的方法

Python

with open('plik.csv', 'rb') as csv_file:
    r = requests.post(https://somelink/companies, data=csv_file)

cURL

curl --header "Content-Type: text/csv" --request POST --data-binary "@test.csv" https://somelink/companies

我做错了

$url = 'https://somelink/companies';

$params = array(
    'key' => '8e7bdd23qa1d06b493152ea37cd4ah39',
    'csv' => file_get_contents('test.csv'),
); 

$query = http_build_query($params);

$ctx = stream_context_create(array(
            'http' => array(
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent: uploader_pmg_companies\r\n",
                'method'  => 'POST',
                'content' => $query,
            ),
        ));

$result = file_get_contents($url, $flags = null, $ctx);

1 个答案:

答案 0 :(得分:0)

Ok I wrote in python some like this
  

导入请求

url = "https://somelink/companies"
files = {'file': open('plik.csv', 'rb')}
payload = {'key': '8e7bdd23qa1d06b493152ea37cd4ah39', 'csv': files}
headers = {'Content-Type: application/x-www-form-urlencoded', 'User-Agent: uploader_pmg_companies'}
r = requests.post(url, params=payload, files=files)
print r.url
print (r.text)
And server answer {"file_csv_content":"file...","status":success"}

So this works?