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>
Related
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>
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.
I have a code which consists of app.py, template folder(index and results).
I am using dropzone to upload my images/videos.
I am facing problems during uploading the images/videos. After i upload it the page doesn't go on results.html to show the uploaded images. Instead it stays on the same page. But the image/video is saved in my directory.
Please have a look through.
app.py:
import os
from flask import Flask, render_template, request, session, redirect, url_for
from flask_dropzone import Dropzone
from flask_uploads import UploadSet
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config.update(
UPLOADED_PATH=os.path.join(basedir, 'uploads'),
# Flask-Dropzone config:
DROPZONE_MAX_FILE_SIZE=1024, # set max size limit to a large number, here is 1024 MB
DROPZONE_TIMEOUT=5 * 60 * 1000 # set upload timeout to a large number, here is 5 minutes
)
app.config['SECRET_KEY'] = 'supersecretkeygoeshere'
app.config['DROPZONE_REDIRECT_VIEW'] = 'results'
dropzone = Dropzone(app)
#app.route('/', methods=['POST', 'GET'])
def index():
#set session for image results
if "filename" not in session:
session['filename'] = []
#list to hold our uploaded image urls
filename = session['filename']
#handle image upload from dropzone
if request.method == 'POST':
f = request.files.get('file')
f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
#append image urls
filename.append(filename.url(filename))
session['filename'] = filename
return "uploading..."
return render_template('index.html')
#app.route('/results')
def results():
#redirect to home if no images to display
if "filename" not in session or session['filename'] == []:
return redirect(url_for('index'))
#set the filename and remove the session variables
filename = session['filename']
session.pop('filename', None)
return render_template('results.html', filename=filename)
if __name__ == '__main__':
app.run(debug=True)
index.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='index') }}
{{ dropzone.load_js() }}
{{ dropzone.config() }}
</body>
</html> ```
results.html:
<html><h1>These are your uploaded images</h1>
Back<p>
<ul>
{% for filenm in filename %}
<li><img style="height: 150px" src="{{ filenm }}"></li>
{% endfor %}
</ul>
</p> </html>
I have tried the existing code, but it still fails. My problem is how to insert data into the .txt file using the Flask form.
The following is my app.py code:
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
input_nopol = request.form.get['nopol']
if request.method == 'POST' and input_nopol:
print(listdir)
with open('/home/pi/web-server/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)
The following is a simple code for the form at index.html in template folder:
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form method="POST">
<input name="text">
<input type="submit">
</form>
</body>
</html>
I am very grateful for the help and solution from all of you.
Update your code as below
index.html
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box">
<input type="submit">
</form>
</body>
</html>
app.py
from flask import Flask, request, render_template
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['text_box']
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.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box">
<input type="submit">
</form>
from flask import Flask, request, render_template
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['text_box']
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.debug = True
app.run()