Flask is not recognizing my form from HTML [duplicate] - python

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 months ago.
I'm working on an upload file function for my web tool and I'm facing an issue. The problem is that Flask is not receiving the files from the HTML form. I have already set the route, and created the form tag accordingly to what is required like the method POST and still not working. Am I doing anything wrong?
HTML
<form action="/" method="POST" enctype="multipart/form-data" class="form-horizontal">
<div class="row form-group">
<div class="col-12 col-md-12">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
Requests
</label>
<div class="controls">
<div class="entry input-group upload-input-group">
<input class="form-control" name="fields[]" type="file">
<button class="btn btn-upload btn-success btn-add" type="button">
<i class="fa fa-plus"></i>
</button>
</div>
</div>
<button class="btn btn-primary" type="submit" value="Submit">Upload</button>
</div>
</div>
</div>
</form>
Python/Flask
import os
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
app=Flask(__name__)
app.secret_key = "secret key"
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
path = os.getcwd()
# file Upload
UPLOAD_FOLDER = os.path.join(path, 'uploads')
if not os.path.isdir(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['xlsx', 'xls'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/')
def upload_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
# 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 file.filename == '':
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('File successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are xlsx and xls')
return redirect(request.url)
if __name__ == "__main__":
app.run(host = '127.0.0.1',port = 5000, debug = False)

Try changing the input name to file instead fields[]
<input class="form-control" name="file" type="file">

Related

Display values of json returned by python file in html webpage seperately

I am making a webapp for OCR on document with layoutlm using flask, website has upload system that accepts images and documents which are later processed by a python file for OCR which returns a JSON containing 'key' as field name like 'Name', 'DOB' and value as corresponding answer to the field as 'Akshit', '17/02/2002'. I have got the upload system working but am not able to figure out how I display these values into my HTML webpage. Can you please help?
app.py:-
from flask import Flask
UPLOAD_FOLDER = r'path\to\upload\folder'
app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
main.py :-
#import magic
import urllib.request
from invoice_docquery import ret_scores
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/')
def upload_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
# 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 file.filename == '':
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
json_ans = ret_scores(filename) # Performs OCR and returns json containing key as field names and value as its corresponding answers
flash('File successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are pdf, png, jpg, jpeg')
return redirect(request.url)
if __name__ == "__main__":
app.run()
HTML code so far (index.html):-
<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Select a file to upload</h2>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
<form method="post" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="file" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>
function 'ret_scores' in main.py returns the required json for which I want to display its values in the HTML webpage
Do let me know if any additional information is required
It's difficult to diagnose exactly what your issue is as you didn't explain what output you're getting (error message? no content showing?), but the issue appears to be in the way you're trying to use the jinja template, in particular in the line:
{% with messages = get_flashed_messages() %}
What is get_flashed_messages() and how does the template know where to find it?
You pass information to templates as parameters in render_template, so your #app.route('/') will need to contain a line like:
return render_template('index.html', messages)
Passing variables between routes gets messy and confusing, so I recommend using session variables to store the information that you will pass to the template.
I've rewritten your code to demonstrate the basic flow, but please don't expect it to run first time as I haven't run it to test. There may still be some debugging to do but hopefully it should demonstrate the general idea and get you moving in the right direction.
app.py looks fine as-is.
main.py:
#import magic
import urllib.request
from invoice_docquery import ret_scores
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/')
def upload_form():
if session['messages']:
return render_template('index.html', messages=session['messages'])
else:
return render_template('index.html', messages={})
#app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
# 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 file.filename == '':
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
session['messages'] = ret_scores(filename) # Performs OCR and returns json containing key as field names and value as its corresponding answers
flash('File successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are pdf, png, jpg, jpeg')
return redirect(request.url)
if __name__ == "__main__":
app.run()
index.html:
<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Select a file to upload</h2>
<p>
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</p>
<form method="post" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="file" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>
Feel free to ask any question is in the comments and I'll do my best to help when I can.

How to Access type="file" Input From Flask App

From my flask app, I need to access the file from the <input type="file">. Whether it be the file data or the actual file. I need to do something like this: http://jsfiddle.net/ugPDx/ but without js
thanks in advance!
Make sure you have created the static folder and inside that folder, you have the uploads folder.
upload.html
<!doctype html>
<title>Python Flask Image Upload and Display Example</title>
<h2>Select an image to upload and display</h2>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
{% if filename %}
<div>
<img src="{{ url_for('display_image', filename=filename) }}">
</div>
{% endif %}
<form method="post" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="file" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>
app.py
import os
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'static/uploads/'
app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/')
def upload_form():
return render_template('upload.html')
#app.route('/', methods=['POST'])
def upload_image():
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#print('upload_image filename: ' + filename)
flash('Image successfully uploaded and displayed')
return render_template('upload.html', filename=filename)
else:
flash('Allowed image types are -> png, jpg, jpeg, gif')
return redirect(request.url)
#app.route('/display/<filename>')
def display_image(filename):
#print('display_image filename: ' + filename)
return redirect(url_for('static', filename='uploads/' + filename), code=301)
if __name__ == "__main__":
app.run()

Flask Upload File Not Found

I want to make a file uploader using Python, Flask, and HTML. If I upload a file I get:
Not Found
The requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
import os
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = './user/Tom/Files/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == ['POST']:
if 'file' not in request.files:
flash('Geen Bestand')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('Geen Bestand')
return redirect(request.url)
if not os.path.exists("user/Tom/Files/"):
os.makedirs("user/Tom/Files/")
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return render_template("index.html")
if __name__ == ('__main__'):
app.run(debug=True, port=8000)
<!DOCTYPE html>
<html>
<head>
<title>Upload a File!</title>
</head>
<body>
<form method="post" action="user/Tom/Files/" enctype="multipart/form-data">
<input type="file" id="customFile" name="file">
<input type="submit" name="Upload" value="Upload">
</form>
</form>
</body>
</html>
I deleted the action and the value
Now i have this:
<form method="post" enctype="multipart/form-data">
<input type="file" id="customFile" name="file">
<input type="submit" name="Upload">
</form>
But now it stay on de index.html but doesnt upload it to /user/Tom/Files/ ?

Python + Flask Image Upload "No file part"

I am new to python/flask and am trying to upload an image for a users profile picture during registration. I've taken the backend flask code related to file uploads directly from their documentation found here. When I perform a registration, I receive the HTTP error:
Bad Request The browser (or proxy) sent a request that this server
could not understand.
And in my python console:
no file part
I am using a bootstrap fork "Upload Image w Preview & Filename" found here. Here is my registration form:
<form action="/register" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" class="form-control" name="confirm-password" id="confirm-password" placeholder="Confirm Password">
</div>
<div class="form-group">
<label>Profile Picture</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
<button class="btn btn-success">Browse…</button>
<input type="file" id="imgInp" name="file">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id='img-upload' style="margin-top: 10px;"/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And here is my backend/flask stuff.
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import secure_filename
import datetime
import os
UPLOAD_FOLDER = '/static/images'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
db = SQL("sqlite:///data.db")
Session(app)
#app.route('/register', methods=['POST'])
def register():
username = request.form.get("username")
password = request.form.get("password")
row = db.execute("SELECT * FROM users WHERE username = :username", username=username)
if not row:
if 'file' not in request.files:
flash('No file part')
print("no file part")
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
print("no selected file")
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
db.execute("INSERT INTO users (username, passwordHash, pictureUrl) VALUES (:username, :passwordHash, 'static/images/default.jpg')", username=username,passwordHash=generate_password_hash(password))
else:
return apology("Username already exists.")
return redirect("/")
Add the attribute enctype='multipart/form-data' to the form tag. As this attribute enforces the proper HTTP request handling of the form.

Python flask and opening/using a file

I am trying to make a web app that reads a selected file into the program and does calculations on the data inputted.
index.html
<body>
<div class="container">
<hr/>
<div>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br /><br />
<input type="submit" value="Upload">
</form>
</div>
</div>
</body>
python file
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods=['GET', 'POST'])
def upload():
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
text_file = open(filename,"r")
Data = text_file.read()
return render_template('base.html',filename=filename)
Here I'm getting the file then saving it locally then opening it and getting the data. I want to get the "Data" into other functions to do calculations on. How do I go about getting my data to other functions?
I would like to have a page saying X file was loaded in then be able to click the tabs on my web app to run the calculations on said file.

Categories