Flask图片显示故障:/home/sally_venka/upload下的logo无法加载
Let’s work through why your "My logo.jpg" isn’t showing up step by step:
1. Fix the Broken HTML Structure
Your index.html has the <body> tag outside the <html> tag, which is invalid and can mess up rendering before we even get to the image path. Correct it to:
<html> <body> <form method="GET" action="/show_index1"> <img src="{{ user_image }}" alt="User Image" width="200" height="85"> </form> </body> </html>
2. Correct the Upload Folder Path
Your server.py uses a relative path for UPLOAD_FOLDER1, but your actual files live in an absolute path (/home/sally_venka/upload). Use an absolute path to avoid confusion:
import os from flask import Flask, render_template, send_from_directory, url_for app = Flask(__name__) # Use absolute path to the upload folder UPLOAD_FOLDER1 = os.path.join('/home', 'sally_venka', 'upload') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER1
3. Add a Route to Serve Uploaded Files
Flask doesn’t automatically serve files from arbitrary folders. You need a dedicated route to return files from your upload directory:
@app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
4. Pass the Correct Image URL to the Template
In your show_index1 route, generate the proper URL for the image using url_for, then pass it to the template:
@app.route('/show_index1', methods=['GET']) def show_index1(): # Generate the URL for your logo logo_url = url_for('uploaded_file', filename='My logo.jpg') # Pass the URL to the template (assuming you're using render_template) return render_template('index.html', user_image=logo_url)
5. Verify File Permissions
Make sure the Flask process has read access to /home/sally_venka/upload/My logo.jpg. Check permissions with:
ls -l /home/sally_venka/upload/My\ logo.jpg
If needed, adjust permissions with:
chmod 644 /home/sally_venka/upload/My\ logo.jpg
After making these changes, restart your Flask server and test again. Most likely, the path misconfiguration and missing file-serving route were the main culprits.
内容的提问来源于stack exchange,提问作者S P

