create a file upload with html form in python

Here is an example of how to create a file upload HTML form using Flask in Python:

main.py
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('form.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    file.save(file.filename)
    return 'File uploaded successfully!'

if __name__ == '__main__':
    app.run(debug=True)
352 chars
17 lines

This code defines two routes: home() which renders an HTML file with a form for file uploading, and upload() which receives the file and saves it to the server.

Here is an example of the form.html file:

<!DOCTYPE html>
<html>
<head>
	<title>File Upload</title>
</head>
<body>
	<h1>File Upload Form</h1>
	<form method="POST" action="/upload" enctype="multipart/form-data">
		<input type="file" name="file">
		<input type="submit" value="Upload">
	</form>
</body>
</html>
267 chars
14 lines

This HTML file defines a form with a file input field and a submit button. The method attribute of the form is set to "POST", the action attribute is set to "/upload", and the enctype attribute is set to "multipart/form-data", which is necessary for handling file uploads.

When the form is submitted, it sends a POST request to the /upload route, which calls the upload() function. The file is retrieved from the request using request.files['file'], and then saved to the server using file.save(file.filename).

Note that this is just a basic example, and you may need to add more error handling and security measures to your code depending on your requirements.

gistlibby LogSnag