1 回答

TA貢獻1812條經驗 獲得超5個贊
我相信您應該將圖像作為路徑名存儲到您的帖子表中,而不是 blob。
在您的數據庫中將其更改為:
link = db.Column(db.String(30))
然后在將帖子添加到數據庫時將圖像文件名路徑的字符串傳遞到帖子中
使用隨機字符串重命名文件也是一個好習慣,因為許多用戶可能會上傳,myCatPicture.jpg這會導致它覆蓋文件。
這樣的事情會做
def get_random_string(length):
# Random string with the combination of lower and upper case
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
然后在保存圖像時保存新文件名
if not allowed_images(image.filename):
flash('Invalid image extension!', 'danger')
return redirect(request.url)
else:
ext = os.path.splitext(file_name)[1] # get the file extension
new_filename = get_random_string(20) # create a random string
image.save(os.path.join(app.config['IMAGE_UPLOADS'], new_filename+ext)) # save with the new path
并在創建后使用新字符串。
post = Post(title=form.title.data,
body=form.body.data, link=os.path.join(app.config['IMAGE_UPLOADS'], new_filename+ext) , user_id=current_user.id) #here we are substituting the old blod with the new stored image path string
筆記:
只要您將路徑存儲在數據庫中,文件名并不重要。您可以隨時查找它以獲取圖像/路徑。
...
然后在你的模板中(因為你已經有了所有的帖子)你可以開始一個 for 循環
{% for post in range(len(posts)) %}
<h1> {{ post.title }} </h1>
<img src= {{post.link }} >
<p> {{ post.body }} </p>
{% endfor %}
這應該遍歷每個帖子標題、圖像和內容等。
同樣,我對此有點模糊。但認為這幾乎涵蓋了它。
添加回答
舉報