2017-05-12 100 views
0

我正在访问一个网站,我想上传一个文件。python请求上传文件

我写在Python代码:

import requests 

url = 'http://example.com' 
files = {'file': open('1.jpg', 'rb')} 
r = requests.post(url, files=files) 
print(r.content) 

但似乎没有文件已被上传,页面是一样的最初一个。

我想知道如何上传文件。

该页面的源代码:

<html><head><meta charset="utf-8" /></head> 

<body> 
<br><br> 
Upload<br><br> 
<form action="upload.php" method="post" 
enctype="multipart/form-data"> 
<label for="file">Filename:</label> 
<input type="hidden" name="dir" value="/uploads/" /> 
<input type="file" name="file" id="file" /> 
<br /> 
<input type="submit" name="submit" value="Submit" /> 
</form> 

</body> 
</html> 
+0

顺便说一句,你没有发送'dir'。 'r = requests.post(url,files = files,data = {“dir”:“/ uploads /”})' – ozgur

+0

@OzgurVatansever我已经添加了数据。但仍然没有文件上传。 –

回答

1

的几点:

  • 确保您的请求提交到正确的URL(形式为“行动”)
  • 使用data参数提交其他表单字段(“目录”,“提交')
  • 包括在files的文件的名称(这是可选的)

代码:

import requests 

url = 'http://example.com' + '/upload.php' 
data = {'dir':'/uploads/', 'submit':'Submit'} 
files = {'file':('1.jpg', open('1.jpg', 'rb'))} 
r = requests.post(url, data=data, files=files) 

print(r.content) 
+0

谢谢。它现在有效。似乎我有错误的网址来上传文件。 –

0

首先,定义上载目录类似的路径,

app.config['UPLOAD_FOLDER'] = 'uploads/' 

然后定义这使得像上传文件的扩展名,

app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 

现在假设你调用函数来处理上传文件,那么你必须编写类似于代码的代码s,

# Route that will process the file upload 
@app.route('/upload', methods=['POST']) 
def upload(): 
    # Get the name of the uploaded file 
    file = request.files['file'] 

    # Check if the file is one of the allowed types/extensions 
    if file and allowed_file(file.filename): 
     # Make the filename safe, remove unsupported chars 
     filename = secure_filename(file.filename) 

     # Move the file form the temporal folder to 
     # the upload folder we setup 
     file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 

     # Redirect the user to the uploaded_file route, which 
     # will basicaly show on the browser the uploaded file 
     return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename)) 

这样您就可以上传文件并将其存储在您所在的文件夹中。

我希望这会帮助你。

谢谢。

+0

感谢您的回复。其实,我只是访问他人拥有的网站。我可以通过浏览器上传文件,但我需要找到一种通过python上传的方法。 –