我创建了一个简单的html上传文件:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
和一个简单的php上传文件:
<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
我测试了一切都很完美 我想使用请求模块使用python提交文件上传,所以我创建了这个:
import requests
url = 'http://localhost/upload/up.html'
files = [('images', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)
print r.text
它将返回html页面代码并且文件上传失败,任何解决方案?
答案 0 :(得分:1)
我认为问题是传递给post
的名称。使用fileToUpload
而不是images
,如下所示:
files = [('fileToUpload', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)