create file upload in python

To create a file upload functionality in Python, you can use a web framework such as Flask to handle the incoming file through a HTTP request. Here's an example code that creates an HTML form that allows the user to select a file and submit it to the application:

<!DOCTYPE HTML>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <form action="/" method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
  </body>
</html>
259 chars
13 lines

In this form, enctype="multipart/form-data" is crucial for uploading files.

Next, in your Python Flask application, you can handle the incoming file using the request module, which should be imported at the top of your file:

main.py
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        # Do something with the file here
        return 'File uploaded successfully'
    return '''
        <html>
          <head>
            <title>File Upload</title>
          </head>
          <body>
            <form action="/" method="post" enctype="multipart/form-data">
              <input type="file" name="file">
              <input type="submit" value="Upload">
            </form>
          </body>
        </html>
        '''
631 chars
24 lines

In the function upload_file(), we check if the HTTP request method is POST, which indicates the form has been submitted. We then get the file object using request.files['file']. From here, you can do various things with the file, such as save it to disk, read its contents, or process it in some way.

Remember to specify the host and port when running your Flask application, or else you won't be able to access it in your web browser:

main.py
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
78 chars
3 lines

gistlibby LogSnag