簡體   English   中英

獲取 Flask 以顯示不在靜態目錄中的圖像

[英]Get Flask to show image not located in the static directory

我正在嘗試顯示位於不是默認靜態文件夾的文件夾中的圖像。

我的模板看起來像:

{% extends "layout.html" %}
{% block body %}
   Albums
   {% for album in albums %}
      <img src="{{ album ['ThumbPath'] }}">
   {% endfor %}
{% endblock %}

生成的 HTML 如下所示:

<!doctype html>
<title>iPhoto</title>
<link rel=stylesheet type=text/css href="/static/style.css">
<div class=page>
<h1>iPhoto</h1>  
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-180444/t264vvMaQM+GJosBP+4q+Q/_DSC1225.jpg">  
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181030/urU3jqSKRgGNNP1MjKhpvg/_DSC1268.jpg">
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181037/1zYyNYReRg+Sizx8v4BUkw/_DSC0923.jpg">  
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181038/sKzEEB3jSf6GBs2heQIviA/Kelly.jpg">
</div>

如何獲取要在生成的網頁上呈現的圖像。 圖片的路徑是正確的。 無法將所有圖像復制到靜態文件夾。

達雷爾

看起來你有文件系統路徑而不是站點。 當您使用/開始資源時,路徑將從站點根目錄開始(站點的絕對路徑,不帶斜杠或使用./../是相對的)例如,如果您有站點http://test.com那么/將是http://test.com//test將是http://test.com/test 您可以使用特定的協議protocol://設置路徑protocol://或為當前站點設置相同的路徑//為其他站點。 您總是可以在瀏覽器錯誤控制台中發現錯誤(完整)網址的錯誤。

要訪問文件系統,您必須使用file://協議,您的網址將類似於file:///Users/Darrell/Pictures/... 但它僅適用於您的計算機並且可能存在安全問題。 您還可以將此文件的符號鏈接設置為靜態文件夾,這可以解決安全問題,但不能僅解決您的計算機的問題。 為了完全解決這個問題,更好地將此文件發布到您的應用程序或公共(私有)Web 服務器上以獲取圖像或其他靜態文件。

所以這是我的項目路徑 我寫了一個簡單的函數,它可以通過在網頁上呈現來工作。 我不是 100% 確定它在部署后是否可以工作,所以我會更新它是否在部署后工作。

 <img alt="" src="{{ url_for('send_file', filename=image_url) }}" id ="img"/>

這是 HTML 元素的代碼,這是它在服務器端的 Python 中的相應代碼。

def getImageName(x):
    """
    Dealing with Unix Path names and Windows PathNames
    """
    if platform.system() == 'Linux':
        return  x[x.rfind("/")+1:]
    return x[x.rfind("\\")+1: ]
      
def getFolder(x):
        y = []
        if platform.system() == 'Linux':
            y = x.split("/")
        else:
            y = x.split("\\")
       # print(y)
        cat_name = ""
        if "roomImage" in x:
            cat_name+="roomImage/" + y[-2]
        elif "lobbyImage" in x:
            cat_name+="lobbyImage"
        elif "miscImage" in x:
            cat_name += "miscImage/" + y[-2]
        elif "washroomImage" in x:
            cat_name += "washroomImage"
        else:
            cat_name += "facadeImage"
        return cat_name + "/"

@app.route("/send_file/<filename>")
def send_file(filename):
   return send_from_directory(app.config["UPLOAD_FOLDER"] +"/" + getFolder(filename) , getImageName(filename))

這在大多數情況下有效。 順便說一句, image_url 應該是圖像的絕對路徑,您可以通過 render_template 作為參數傳遞給 Jinja2 模板,如下所示:

return render_template("/contentpage.html",image_url=imgurl)

不要忘記導入 send_from_directory 並將 app.config["UPLOAD_FOLDER"] 設置為適當的目錄。 這不是最有效的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM