Error while uploading image file using Flask - python

Error
while uploading files to my selected folder it raises the following error.
As I am new to flask I am unable to catch the error.
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
app.py
import os
#import magic
import urllib.request
#from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
app = Flask(__name__)
#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
UPLOAD_FOLDER = '/static'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', '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_file():
if request.method == 'POST':
# check if the post request has the files part
if 'files[]' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('files[]')
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('File(s) successfully uploaded')
return redirect('/')
if __name__ == "__main__":
app.run(debug = True)
upload.html
<!doctype html>
<title>Python Flask Multiple Files Upload Example</title>
<h2>Select file(s) 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="files[]" multiple="true" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>

You should change your code
#app.route('/', methods=['POST', 'GET'])
def upload_file():
if request.method == 'POST':
# check if the post request has the files part
if 'files[]' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('files[]')
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('File(s) successfully uploaded')
return redirect('/')
elif request.method == 'GET':
return render_template('upload.html')

Related

Method not allowed 405 Error in Flask Api

I am currently trying to upload a picture and later on process it. But I am getting an 405 error and I don't know how to fix it.
#app.route('/upload')
def upload():
return render_template('upload.html')
#app.route('/uploader', methods = ['GET', 'POST'])
def upload_f():
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
return 'file uploaded successfully'
The html form
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
From Miguel Grinberg's Handling File Uploads With Flask tutorial:
import imghdr
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['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'
def validate_image(stream):
header = stream.read(512) # 512 bytes should be enough for a header check
stream.seek(0) # reset stream pointer
format = imghdr.what(None, header)
if not format:
return None
return '.' + (format if format != 'jpeg' else 'jpg')
#app.route('/')
def index():
files = os.listdir(app.config['UPLOAD_PATH'])
return render_template('index.html', files=files)
#app.route('/', methods=['POST'])
def upload_files():
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'] or \
file_ext != validate_image(uploaded_file.stream):
abort(400)
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
return redirect(url_for('index'))
#app.route('/uploads/<filename>')
def upload(filename):
return send_from_directory(app.config['UPLOAD_PATH'], filename)
<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>
{% for file in files %}
<img src="{{ url_for('upload', filename=file) }}" style="width: 64px">
{% endfor %}
</body>
</html>

Flask - pass variables to routes

I'm trying to make a page that will allow a user to download files that have been uploaded. Currently, I'm finding all of the files within a directory, passing them to the index page and printing them out. I then want each to have a download button, that when clicked will download the file relative to the file name. I cannot figure out how to pass the file name back through a URL so that I can use it on the download page.
import os
from flask import Flask, flash, render_template, url_for, request, redirect, send_from_directory, send_file, abort
from werkzeug.utils import secure_filename
import logging
UPLOAD_FOLDER = './uploads/'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config["ALLOWED_EXTENSIONS"] = {'TXT', 'PDF', 'DOC', 'DOXC', 'BIBTEXT', 'DBLP'}
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
files = []
with os.scandir('uploads/') as entries:
for entry in entries:
files.append(entry)
return render_template('index.html', files=files)
else:
return render_template('index.html')
def allowed_ext(filename):
if not "." in filename:
return False
ext = filename.rsplit(".", 1)[1]
if ext.upper() in app.config["ALLOWED_EXTENSIONS"]:
return True
else:
return False
#app.route('/upload', methods=['POST','GET'])
def upload_file():
if request.method == "POST":
if request.files:
file = request.files['file']
if file.filename == "":
print("File name must not be blank")
return redirect(request.url)
if not allowed_ext(file.filename):
print("File extension not supported")
return redirect(request.url)
else:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print("File saved")
return render_template('index.html')
else:
return render_template('upload.html')
#app.route('/download/<file_name>', methods=['GET', 'POST'])
def download_file(file_name):
file_name = file_name
try:
return send_from_directory(app.config['UPLOAD_FOLDER'], filename=file_name, as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == "__main__":
app.run(debug=True)
{% extends 'base.html' %}
{% block head%}<title>File thingy</title>{% endblock %}
{%block body%}
<h4 style='text-align: center;'> Directory Reader</h4>
{% if files is not defined %}
<h2 style='text-align: center;'>Click the button below to analyse the upload directory!</h4>
{% else %}
{% if files|length < 1 %}
<h2 style='text-align: center;'>No files found in this directory!</h4>
{% else %}
<table>
{% for file in files %}
<tr>
<td>{{file}}</td>
<td>
<a href='{{url_for(download_file, file_name=file)}}'>Download</a>
</tr>
{% endfor %}
</table>
{% endif %}
{% endif %}
<form action='/' method = 'POST'>
<input type='submit' name='submitbutton' value='See Files'>
</form>
<button type="button" ><a href='/upload'>Upload file!</a></button> {% endblock %}

I am having trouble loading the Flask image

I uploaded the Uploading Files document for photo albums in the project. İmage upload is not working.
Python Code :
UPLOAD_FOLDER = '/static/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#Album form
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route("/admin/fotografAlbumu", methods=["GET", "POST"])
#login_required
def upload():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['photo']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
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))
import pdb;pdb.set_trace()
return redirect(url_for('uploaded_file', filename=filename))
return render_template('/admin/galeri.html')
HTML Code :
<form method="post" class="col-12" enctype="multipart/form-data">
<ul class="row">
<li class="col-xs-6 col-lg-12" style="border: none;">
<div class="form-group">
<input id="input-id" type="file" name="photo" class="file form-control" multiple data-preview-file-type="text" data-allowed-file-extensions='["png", "jpg"]'>
</div>
</li>
</ul>
<button type="submit" class="btn form-control btn-default">Kaydet</button>
</form>
Output : When I select images on the page and upload them, they redirect to the same page and the images are not loaded. What do I have to do? I'm working on 2 - 3 days, but I can not find a solution.
I took a few minutes to get it working, and here you go:
python:
import os
from flask import Flask, request, render_template, send_from_directory, redirect, url_for
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#Album form
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route("/photo", methods=["GET", "POST"])
def upload():
if request.method == 'POST':
if 'photo' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['photo']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
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))
return redirect(url_for('uploaded_file', filename=filename))
return render_template('/add_photo.html')
#app.route('/uploaded_file/<path:filename>')
def uploaded_file(filename):
print(filename)
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
html:
<form method="post" class="col-12" enctype="multipart/form-data">
<ul class="row">
<li class="col-xs-6 col-lg-12" style="border: none;">
<div class="form-group">
<input id="input-id" type="file" name="photo" class="file form-control" multiple data-preview-file-type="text" data-allowed-file-extensions='["png", "jpg"]'>
</div>
</li>
</ul>
<button type="submit" class="btn form-control btn-default">Kaydet</button>
</form>
Main issue was the fact that you were trying to get file out of the form, but the form only had a field named photo.

Display Submitted Image on Redirected Page via Flask and html [duplicate]

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Closed 5 years ago.
I'm attempting to create a page that takes in a user-submitted image, and automatically redirects them to a new page where the image is rendered. Much of my code is borrowed from here: How to pass uploaded image to template.html in Flask. But I can't seem to get it to work; I run into a 400: Bad Request. It seems to me that the image is not saving under /static/images, but I am not sure why.
Here is the submission form in index.html:
<form method="POST" action="{{ url_for('predict') }}" enctype="multipart/form-data">
<label for="file-input" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Upload Image
</label>
<input name="image-input" id="file-input" type="file" align="center" onchange="this.form.submit();">
</form>
Here is my app.py code:
from flask import Flask, render_template, request, url_for, send_from_directory, redirect
from werkzeug import secure_filename
import os
UPLOAD_FOLDER = '/static/images/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'tiff'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route('/')
def index():
return render_template("index.html")
#app.route('/predict/', methods=['POST', 'GET'])
def predict():
if request.method == 'POST':
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))
return redirect(url_for('uploaded_file', filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
#app.route('/show/<filename>')
def uploaded_file(filename):
return render_template('classify.html', filename=filename)
#app.route('/uploads/<filename>')
def send_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
if __name__ == '__main__':
app.run(debug=True)
And finally, I try to render it in classify.html, with the following code:
{% if filename %}
<h1>some text<img src="{{ url_for('send_file', filename=filename) }}"> more text!</h1>
{% else %}
<h1>no image for whatever reason</h1>
{% endif %}
Where am I going wrong here?
Looks like I was missing an argument in my input: name=file in index.html. Adding that fixed the error. Altogether, the input line looks like this:
<input id="file-input" name=file type="file" align="center" onchange="this.form.submit();">

Reference user supplied file with Flask app

I am new to Flask and web applications in general. I have images that could be located in different locations:
-directory1
-image1
-directory2
-subdirectory
-image2
-directory3
-flask_app
-app.py
-static
The purpose of the app is to dynamically provide access to the content in other directories which is not static and subject to change for each user. The content cannot be moved or modified.
How do I display images from other directories within the app without moving or modifying them based on input values from the user?
I have the following so far but the image link is broken:
from flask import Flask, render_template, request, send_from_directory
current_filepath = /directory2/image{}.png
app = Flask(__name__, static_url_path='')
#app.route('/js/<path:filename>')
def download_file(filename):
return send_from_directory('js', filename)
#app.route('/', methods=['GET','POST'])
def print_form():
if request.method == 'POST':
test = current_filepath.format(request.form['image_num'])
return render_template('form.html', result=test)
if request.method == 'GET':
return render_template('form.html')
if __name__ == '__main__':
app.run(debug=True)
With the following form.html file:
<!DOCTYPE html>
<html lang="en">
<body>
<form method="POST" action=".">
<input id="post_form_id" name="image_num" value="" />
<input type="submit">
</form>
{% if result %}
{{ url_for('download_file', filename= result) }}
<img src={{ url_for('download_file', filename= result) }}>
{% endif %}
</body>
</html>
app/
app.py
...
uploads/
dir1/
img1.png
...
...
app.config['UPLOAD_FOLDER'] = 'path/to/uploads/dir1'
#app.route('/file/<path:filename>')
def img_file(filename):
filename = filename + '.png'
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#app.route('/', methods=['GET', 'POST'])
def index():
filename = None
if request.method == 'POST':
filename = request.form['img_num']
return render_template('form.html', filename=filename)
<form method="post" action="" >
<input type="text" id="form_id" name="img_num">
<input type="submit" value="submit">
</form>
{% if filename %}
<img src=" {{ url_for('img_file', filename=filename) }}">
{% endif %}

Categories

Resources