Итак, я пытался создать пользовательский интерфейс, в котором пользователь мог бы загружать свои изображения в локальную систему (чтобы перейти из одного места в базу данных изображений, открыв диалоговое окно файлового менеджера) или делать живые изображения и добавлять к изображениям база данных. Я сделал этот простой html файл, который работает нормально, но после того, как я попытался запустить его с flask после создания localhost, google chrome не запрашивает разрешение камеры сверху, и каким-то образом разрешение уже предоставлено, но камера не работает Вот код app.py
import os
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
return render_template("upload.html")
@app.route("/upload", methods=["POST"])
#for the intake of the folder name that needs to be created or selected in the dataset folder
def upload():
fold_nam=request.form["name"]
folder_name = request.form.get('superhero')
'''
# this is to verify that folder to upload to exists.
if os.path.isdir(os.path.join(APP_ROOT, 'files/{}'.format(folder_name))):
print("folder exist")
'''
#Change this target variable as per the device working in (set your own path address of the dataset folder)
target="/home" + str(fold_nam).lower()
print(target)
if not os.path.isdir(target):
os.mkdir(target)
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
# This is to verify files are supported
ext = os.path.splitext(filename)[1]
if (ext == ".jpg") or (ext == ".png"):
print("File supported moving on...")
else:
render_template("Error.html", message="Files uploaded are not supported...")
destination = "/".join([target, filename])
print("Accept incoming file:", filename)
print("Save it to:", destination)
upload.save(destination)
# return send_from_directory("images", filename, as_attachment=True)
return render_template("complete.html", image_name=filename)
if __name__ == "__main__":
app.run(port=4555, debug=True)
index. html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="frm1" action="/action_page.php">
Name: <input type="text" name="fname"><br>
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<script type="text/javascript">
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
</form>
<div class="container">
<video id="video" width="300" height="300" autoplay="true"></video>
<button class="button" id="snap">Photo</button>
<canvas id="canvas" width="300" height="300"></canvas>
<br>
<a id="download" href="/images/myw3schoolsimage.jpg" download>download</a>
<div>
<input type="submit" value="Upload!" id="upload-button"><br>
</body>
<script>
$("#file-picker").change(function () {
var input = document.getElementById('file-picker');
for (var i = 0; i < input.files.length;i++) {
//koala.jpg, koala.JPG substring(index) lastIndexOf('a') koala.1.jpg
var ext = input.files[i].name.substring(input.files[i].name.lastIndexOf('.') + 1).toLowerCase()
if((ext == 'jpg') || (ext == 'png')) {
$("#msg").text("Files are supported")
}
else {
$("#msg").text("Files are NOT supported")
document.getElementById("file-picker").value = "";
}
}
});
</script>
<script src="./index.js"></script>
</html>
index. js
(() => {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = document.getElementById("img")
var download = document.getElementById("download")
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
video.srcObject = stream;
video.play();
});
}
document.getElementById("snap").addEventListener("click", () => {
context.drawImage(video, 0, 0, 300, 300);
img.setAttribute("src", canvas.toDataURL("image/png"))
download.setAttribute("href", canvas.toDataURL("image/png"))
});
})()
Все, что я хочу, это чтобы запустите ** index. html **, используя flask с правильно работающей камерой в localhost.
Я знаю, что мой код не в готовом состоянии, но я застрял в этом самом месте , Я хотел бы отметить, что все мои файлы находятся в надлежащих каталогах, и у меня нет ошибок отступов и т. Д. c. Всех, кто хочет помочь, просят упоминать каждую мелочь, потому что я не очень хорош в этом. Thankyou!