I have one HTML form through which the user can upload an image but I don't want the to reload or refresh after the form submission. Here's my HTML form:
<html>
<head>
<title>upload</title>
</head>
<body>
<form action = "/success" method = "post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type = "submit" value="Upload">
</form>
</body>
</html>
And here's my flask app:
from flask import *
from werkzeug.utils import secure_filename
import os
import skimage
import os.path
from os import path
from PIL import Image
import random
import imageio
app = Flask(__name__)
UPLOAD_FOLDER = './flask app/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def upload():
return render_template("index.html")
@app.route('/success', methods = ['GET', 'POST'])
def success():
if request.method == 'POST':
model = load_model()
f = request.files['file']
filename = secure_filename(f.filename)
print(filename)
f.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
image = skimage.io.imread(UPLOAD_FOLDER+'/'+filename)
results = model.detect([image], verbose=1)
r = results[0]
#visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], r['scores'])
path, dirs, files = next(os.walk(UPLOAD_FOLDER))
file_count = len(files)
image_name = 'segmented_image'+str(file_count)+'.jpg'
class_names = ['BG', '0', '1', '2', '3', '4', '5']
n = random.randint(0,100)
folder_name = '/segmentation'+str(n)
os.chdir(UPLOAD_FOLDER)
dir_name = UPLOAD_FOLDER + folder_name
os.mkdir(dir_name)
os.chdir(dir_name)
visualize.save_image(image, image_name, r['rois'], r['masks'], r['class_ids'], r['scores'], class_names=class_names, save_dir=dir_name)
for i in range(r['rois'].shape[0]):
n = random.randint(0, 100)
img = image[r['rois'][i][0]:r['rois'][i][2], r['rois'][i][1]:r['rois'][i][3]]
fname = 'seg'+ str(n)+'.jpg'
imageio.imwrite(fname, img)
return render_template("index.html", name = f.filename)
if __name__ == '__main__':
app.run(debug = True)
The uploaded image is saved successfully but the HTML page reloads which I don't want. Thanks in advance.