1

As we all know the simplest way to upload a file in php is with this code :

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

I want a method to upload a file with python the simplest as possible, a file from the current directory like this:

import anyuploadmodule
upload(file)

Is there a such module can do this ?

1
  • 2
    Try requests. Commented Nov 25, 2014 at 21:28

1 Answer 1

3

There isn't anything quite that simple out there, but micro-frameworks like Flask can be lightweight and simple starting points. You'll want to checkout the documentation. Here's a snippet to get you started:

# -*- coding: utf-8 -*-

import os

from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/some/path/'

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))
    return '''<!doctype html>
              <title>Upload new File</title>
              <h1>Upload new File</h1>
              <form action="" method=post enctype=multipart/form-data>
                <p><input type=file name=file>
                <input type=submit value=Upload>
              </form>'''

if __name__ == '__main__':
    app.run()
Sign up to request clarification or add additional context in comments.

4 Comments

thanks xj9 but it didnt work :/ i added r.text and i keep get the html script code : <!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>
Do you want to upload a file using Python or do you want to upload a file using an HTML form and save or process it using Python?
yes processing it like a post in html form with python
uploaded_file should be upload_file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.