如何使用python(3.8)使用enctype ='multipart / form-data'填写表单?

时间:2019-11-20 15:42:31

标签: php python html

我正在尝试填写此表格

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="text" name="id"></input><br />
    <input type="submit" value="Upload" name="upload"></input>
  </form>

在python 3.8中以这种方式使用request.post()

import requests
path = "my\\path\\file.example"
id = str(input("Your id: "))
url = "http://mysite.example/upload.php"
file = {'uploaded_file': open(path, "rb"), 'id': id}
requests.post(url, files=file)

但它不起作用。

如果我手动填写表格可以正常工作,我还会向您显示upload.php的PHP代码:

<?php
    if(!empty($_FILES['uploaded_file'])){

        $id = $_POST['id'];
        $path = "users/".$id."/files/";
        $path = $path . basename( $_FILES['uploaded_file']['name']);

        if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)){

            echo "The file '".  basename( $_FILES['uploaded_file']['name']).
            "' has been uploaded in path: ".$path."\n";

        }else{
            echo "There was an error uploading the file, please try again!";
        }
    }
?>

我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

files=中,您应该仅发送file,而不发送id

files={'upload_file': open(path, "rb")}

最终包含有关此文件的一些信息

files={'upload_file': ('foobar.txt', open(text,'rb'), 'text/plain')}

id应该位于data=中(最终位于json=params=中)

data={'id': id}

BTW::在PHP中,您可以添加显示从客户端获取的值的代码,然后查看form的数据和{{1}的数据之间是否存在差异}