【发布时间】:2019-11-20 15:42:31
【问题描述】:
我正在尝试填写此表格
<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 中以这种方式使用 requests.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!";
}
}
?>
我哪里做错了?
【问题讨论】:
-
也许在 PHP 中添加代码来显示你得到的值,然后你会看到是否有差异。
-
input()总是给出字符串,所以不需要使用str() -
在
files=中您应该只发送文件,而不是id。id应该在data= -
我在
requests.post(url, files=file, data={'id':id})改了代码,现在可以用了,非常感谢!