【问题标题】:Flask navigate through images in static folder using buttonsFlask 使用按钮浏览静态文件夹中的图像
【发布时间】:2021-03-15 23:53:38
【问题描述】:

我正在使用 Flask 在 Python 中构建一个简单的图像导航器应用程序。我希望有前进和后退按钮来浏览静态文件夹中的所有图像。到目前为止,我只有一个按钮,可以在不刷新页面的情况下显示图像。如何使用按钮浏览目录?

app.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def hello():
    return render_template('upload.html')

@app.route("/getimage")
def get_img():
    return "00621.jpg"


if __name__ == '__main__':
    app.run()

上传.html

<!DOCTYPE html>
<html lang="en">
<style>
img {
    max-width: 100%;
    max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script>
    $(document).ready(function() {
       $('#retrieve').click(function(){
           $.ajax({
           url: "{{ url_for ('get_img') }}",
           type : 'POST',
           contentType: 'application/json;charset=UTF-8',
           data : {'data':{{}}}
           success: function(response) {
               $("#myimg").attr('src', 'static/' + response);
          },
          error: function(xhr) {
            //Do Something to handle error
         }
         });
       });
    });
  </script>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

</head>
<body>
<div class="container">

    <div class="row">

        <div class="col-lg-12">
            <h1 class="page-header">Image Annotator</h1>
        </div>
        <button type='button' id ='retrieve'>Submit</button>
     <img src="" id="myimg" />
    </div>
</div>

     
   </body>
 
</html>

【问题讨论】:

  • 可能值得看看引导程序中的carousel 组件。那么这只是将文件列表传递给模板的一个例子,用[f for f in os.listdir('static') if f.endswith('.jpg')]之类的东西抓取,如果这适合你,我可以给出更具体的答案?

标签: python flask


【解决方案1】:

我已经重构了你的一些代码来获得答案。请注意,我已将内容从 Jquery 切换到 JS。

新的 HTML 页面:

<!DOCTYPE html>
<html lang="en">
<style>
img {
    max-width: 100%;
    max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

</head>
<body>
<div class="container">

    <div class="row">

        <div class="col-lg-12">
            <h1 class="page-header">Image Annotator</h1>
        </div>
        <button type='button' onclick="oclick()" id='retrieve'>Submit</button>
     <button onclick="action(2)" type="button">Backward</button><button onclick="action(1)" type="button">Forward</button>
     
     <image src="" id="myimg"></image>
    </div>
</div>
<script>
var imgap = 0

function oclick(){
var getInitialImage = new XMLHttpRequest();
getInitialImage.open("GET", "/getimage");
getInitialImage.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getInitialImage.send();
}

function action(ac){
if (ac == 1){
imgap += 1
var getnextimagedetails = new XMLHttpRequest();
getnextimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getnextimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getnextimagedetails.send();
}
if (ac == 2){
imgap += -1
var getlastimagedetails = new XMLHttpRequest();
getlastimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getlastimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getlastimagedetails.send();
}
}
</script>
        </body>
 
</html>

新建 Flask 文档:

from flask import Flask, send_from_directory, request
import os
app = Flask(__name__)


@app.route("/")
def hello():
    return send_from_directory('', 'upload.html')

@app.route("/image/<path:path>")
def image(path):
    print(path)
    if (path.endswith(".jpg") or path.endswith(".png") or path.endswith(".bmp") or path.endswith(".jpeg")):
        return send_from_directory("", path)
    return "", 500

@app.route("/getimage")
def get_img():
    print(request.args.get("num"))
    if (request.args.get("num") != None):
        dirfiles = os.listdir()
        presentedstr = []
        for string in dirfiles:
            if (string.endswith(".jpg") or string.endswith(".svg") or string.endswith(".bmp") or string.endswith(".jpeg") or string.endswith(".png")):
                presentedstr.append(string)
        presentedstr.index("00621.jpg")
        return presentedstr[presentedstr.index("00621.jpg") + int(request.args.get("num"))]
    else:
        return "00621.jpg"


if __name__ == '__main__':
    app.run()

这个实现的工作原理是,按钮会在对实际的下一个图像本身发出另一个请求之前,向服务器发送一个请求以获取下一个图像或项目是什么。它将搜索同一目录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2014-06-06
    • 2019-09-19
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多