::: code for image upload

Here’s a minimal and complete example of image upload functionality using HTML and Python (Flask):


🔧 1. app.py (Python Flask Backend)

python
from flask import Flask, render_template, request, redirect, url_for
import os

app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def upload_form():
return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_image():
if 'image' not in request.files:
return 'No file part'

file = request.files['image']

if file.filename == '':
return 'No selected file'

if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath)
return f'File uploaded successfully: <a href="/{filepath}">{file.filename}</a><br><img src="/{filepath}" width="300">'

return 'Upload failed'

if __name__ == '__main__':
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.run(debug=True)

🖼️ 2. templates/upload.html

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<h2>Upload an Image</h2>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<input type="submit" value="Upload">
</form>
</body>
</html>

📁 Folder Structure

cpp
project_folder/
│
├── app.py
├── static/
│ └── uploads/ ← Uploaded images saved here
└── templates/
└── upload.html ← Upload form

✅ How to Run

  1. Install Flask if you haven’t: bashCopyEditpip install flask
  2. Run the server: bashCopyEditpython app.py
  3. Open http://localhost:5000 in your browser.

Let me know if you need:

  • drag-and-drop upload
  • image preview before upload
  • upload to cloud (like S3)
  • support for React / Vue / Swift / Flutter instead of Flask