How to upload files

How to let users upload their image files into a specific directory

I was making a project but I got very little of images for me to upload, I want to let users upload their image, and only image files, to a specific directory, how can I do that?

Hey, @TaokyleYT! It would help if you could share a link to the cover page of your Repl so we can have more context

Well I just need the html code for uploading but sure

I just needed to know how your backend was structured. Flask actually already has a great tutorial on file uploads which tells you how to restrict file types and upload it to a specific directory:

1 Like

Hello there. In Flask, you can handle file uploads using the Flask module’s request object, which represents an incoming HTTP request. You can access the uploaded files using the request.files attribute, which is a dictionary-like object containing all the uploaded files.

Here’s an example code snippet that demonstrates how to handle file uploads in Flask:

from flask import Flask, render_template, request
import os

app = Flask(__name__)

# Set the path to the directory where you want to store the uploaded files
UPLOAD_FOLDER = '/path/to/your/upload/folder'

# Set the allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

# Set the maximum file size (in bytes) that you want to allow
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB


# Define a function to check if the file extension is allowed
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    # Check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    # If the user does not select a file, the browser submits an empty file without a filename
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        # Save the uploaded file to the UPLOAD_FOLDER directory['UPLOAD_FOLDER'], file.filename))
        flash('File uploaded successfully')
        return redirect('/')
        flash('Invalid file type')
        return redirect(request.url)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.