python requests upload file

六眼飞鱼酱① 提交于 2019-12-10 22:33:09

问题


I'm visiting a website and I want to upload a file.

I wrote the code in python:

import requests

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

But it seems no file has been uploaded, and the page is the same as the initial one.

I wonder how I could upload a file.

The source code of that page:

<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>

回答1:


A few points :

  • make sure to submit your request to the correct url ( the form 'action' )
  • use the data parameter to submit other form fields ( 'dir', 'submit' )
  • include the name of the file in files ( this is optional )

code :

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)



回答2:


First of all, define path of upload directory like,

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

Then define file extension which allowed to upload like,

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

Now suppose you call function to process upload file then you have to write code something like this,

# 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))

This way you can upload your file and store it in your located folder.

I hope this will help you.

Thanks.



来源:https://stackoverflow.com/questions/43938742/python-requests-upload-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!