I am trying to make the webpage in a way that I can access some images, which are saved in the 'static/images' folder, via a hyperlink embedded under their respective names. I tried embedding a link in a page like this but the webpage had a very small icon that didn't show the image.
<!DOCTYPE html>
<html>
<body>
go
</body>
</html>
from flask import Flask, render_template, session, redirect, request, url_for
import pandas as pd
import os
IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER
#app.route('/',methods=["GET"])
def homePage():
return render_template("index.html")
#app.route('/')
#app.route('/goto/<name>')
def show_index(name):
file = name
full_filename = os.path.join(app.config['IMG_FOLDER'], file)
return render_template("goto.html", user_image = full_filename)
if __name__ == "__main__":
app.run(debug=True)
<!DOCTYPE html>
<html>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
On the contrary, when I am using this in the following way it shows up fine -
from flask import Flask, render_template, session, redirect, request, url_for
import pandas as pd
import os
IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER
#app.route('/',methods=["GET"])
def homePage():
return "hello"
#app.route('/')
#app.route('/goto')
def show_index():
file = 'Koala.png'
full_filename = os.path.join(app.config['IMG_FOLDER'], file)
return render_template("goto.html", user_image = full_filename)
if __name__ == "__main__":
app.run(debug=True)
I may be doing something wrong somewhere. Any help would be much appreciated. I am trying to embed these names in the form of for loop in a data-frame. Anyway, thanks in advance!
full_filename = os.path.join(app.config['IMG_FOLDER'], file) will return static\images\file. However, what you need is: \static\images\file. Therefore, what you need to run is:
full_filename = "\\" + os.path.join(app.config['IMG_FOLDER'], file).
Alternatively, if you want to display the image and have a link to goto, you could do the following:
<!DOCTYPE html>
<html>
<body>
<a href="/goto/{{user_image.split('\\')[3]}}">
<img src="{{user_image}}" alt="User Image">
</a>
</body>
</html>
Related
I'm new in Flask, I want to take single file that have been uploaded in my upload path. Then i want to read and send it to my html after hr tag. How can i do that?
This is My Code:
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_EXTENSIONS'] = ['.txt', '.doc']
app.config['UPLOAD_PATH'] = 'uploads'
#app.route('/')
def home():
files = os.listdir(app.config['UPLOAD_PATH'])
return render_template('home.html', content=files)
#app.route('/', methods=['POST'])
def upload_file():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in app.config['UPLOAD_EXTENSIONS']:
abort(400)
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
return redirect(url_for('home'))
if __name__ == "__main__":
app.run()
And This one is my HTML Page:
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
<hr>
{{ content }}
</body>
</html>
It saves the data, but I can't access the data since I use this codefiles = os.listdir(app.config['UPLOAD_PATH'])
You need a variable route that will accept the a filename like #app.route('/<filename:filename>').
You then need to get the file with that name from your upload directory like file_path = os.path.join('UPLOAD_PATH', filename).
Then you need to read the contents of that file and pass it into your view.
with open(file_path) as file:
content = file.read()
Then you can access it in your HTML file and display it.
<p>{{ content }}</p>
Here is a complete example of the route I described:
#app.route('/<filename:filename>')
def display_file(filename):
file_path = os.path.join('UPLOAD_PATH', filename)
with open(file_path) as file:
content = file.read()
return render_template('display_file.html', content=content)
I want to render an image from gridfs on my html pyge using flask.
I store the image in my mongodb using gridfs with one button and also store the ObjectId of the image in a serverside session using Flask-Session.
When I click on another button, I get the correct ObjectId of the image stored before via my session and then want to render this image from gridfs in my html page, but I don't know how to do it.
My app.py file:
from flask import Flask, render_template, request, redirect, session
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from gridfs import GridFS
from flask_session import Session
DB = 'test-grid'
COLLECT = 'test-session'
client = MongoClient('mongodb://127.0.0.1:27017')
db = client[DB]
fs = GridFS(db)
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16*1024*1024
app.config['SESSION_TYPE'] = 'mongodb'
app.config['SESSION_MONGODB'] = client
app.config['SESSION_MONGODB_DB'] = DB
app.config['SESSION_MONGODB_COLLECT'] = COLLECT
Session(app)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f_id = fs.put(f, filename=filename)
session['f_id'] = f_id
session['filename'] = filename
return redirect('/')
#app.route('/display', methods=['GET'])
def display_file():
if request.method == 'GET':
f = fs.get(session['f_id'])
image = f.read()
return render_template("index.html", user_image=image)
if __name__ == "__main__":
app.run(debug=True)
My index.html file:
<html lang='en'>
<head>
<meta charset='UTF-8'/>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="file" autocomplete="off" required>
</form>
<form method="get" action="/display">
<input type="submit" value="Display">
</form>
<img src="{{ user_image }}" alt="Show image here"/>
</body>
</html>
My requirements.txt file:
Flask
Flask-Session
pymongo
But this doesn't work and I get the following output:
Output
Can someone please help me fix this? Maybe with examples I can look up.
So I have uploaded an image into the uploads folder with flask dropzone and I want to be able to pass it to my makeMeme page so I can then display that image using the html img tag. Here is how I upload my image, and attempt to pass it. However when I run a basic img take and try to reference file I get an error.
Here is the Attribute Error I get:
AttributeError: 'NoneType' object has no attribute 'filename'
Here is my main python page.
import os
from flask import Flask, render_template,request, url_for
from flask_dropzone import Dropzone
app = Flask(__name__)
app.secret_key = 'key'
dir_path = os.path.dirname(os.path.realpath(__file__))
app.config.update(
UPLOADED_PATH=os.path.join(dir_path, 'uploads'),
# Flask-Dropzone config:
DROPZONE_ALLOWED_FILE_TYPE='image',
DROPZONE_MAX_FILE_SIZE=3,
DROPZONE_MAX_FILES=20,
DROPZONE_UPLOAD_ON_CLICK=True
)
app.config['DROPZONE_REDIRECT_VIEW'] = 'makeMeme'
dropzone = Dropzone(app)
#app.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
f = request.files.get('file')
file = f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
return render_template('upload.html', file_name = file)
#app.route('/makeMeme', methods=['POST', 'GET'])
def makeMeme():
return render_template("makeMeme.html")
First create templates and static folder
Then copy the upload.html and makeMeme.html inside templates
Then execute the app.py
I hope this will solve your problem
app.py
import os
from flask import Flask, render_template,request, url_for
from flask_dropzone import Dropzone
app = Flask(__name__)
app.secret_key = 'key'
dir_path = os.path.dirname(os.path.realpath(__file__))
app.config.update(
UPLOADED_PATH=os.path.join(dir_path, 'static'),
# Flask-Dropzone config:
DROPZONE_ALLOWED_FILE_TYPE='image',
DROPZONE_MAX_FILE_SIZE=3,
DROPZONE_MAX_FILES=20
)
app.config['DROPZONE_REDIRECT_VIEW'] = 'makeMeme'
dropzone = Dropzone(app)
filename = None
#app.route('/upload', methods=['POST', 'GET'])
def upload():
global filename
file = None
if request.method == 'POST':
f = request.files.get('file')
file = f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
filename = f.filename
return render_template('upload.html')
#app.route('/makeMeme', methods=['POST', 'GET'])
def makeMeme():
global filename
return render_template("makeMeme.html", file_name = filename)
app.run(debug=True)
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask-Dropzone Demo</title>
{{ dropzone.load_css() }}
{{ dropzone.style('border: 2px dashed #0087F7; margin: 10%; min-height: 400px;') }}
</head>
<body>
{{ dropzone.create(action='upload') }}
{{ dropzone.load_js() }}
{{ dropzone.config() }}
</body>
</html>
makeMeme.html
<!DOCTYPE html>
<html>
<img src="{{url_for('static',filename=file_name)}}" alt="Fail">
</html>
How do we execute or run python code after the submit button is pressed the html form that I created in index.html.
The following is the index.php code:
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="nopol">
<input id="print_nopol" type="submit">
</form>
<?php
system("python /home/pi/python-epson-printer/epson_printer/testpage.py");
?>
</body>
</html>
and below is a python flask application script with the name app.py :
from flask import Flask, request, render_template, Response, redirect, url_for
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['nopol']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == "__main__":
app.run(host='192.168.1.2', port=8080, debug=True)
This python code has a function to insert data into a .txt file and here is the python script path:
/home/pi/server_print/print.py
Thank you for your help.
This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 5 years ago.
I am trying to pass a filename of an image and render it on a template,
Although I am passing the actual name through it does not display on the page
#app.route('/', methods=['GET','POST'])
#app.route('/start', methods=['GET','POST'])
def start():
person_to_show = 'tim'
profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg")
return render_template('start.html',profilepic_filename =profilepic_filename )
For example: profilepic_filename = /data/tim/img.jpg
I have tried
{{profilepic_filename}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>
And I have also tried
<img src="{{profilepic_filename}}"></img>
Neither of which worked
I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template.
In application.py:
from flask import Flask, render_template
import os
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
#app.route('/')
#app.route('/index')
def show_index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg')
return render_template("index.html", user_image = full_filename)
In index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
Output: