问题
What I am trying to do is to keep changing the background image using image files that are uploaded in the database instead in the 'static', 'images'
folder.
I obviously can't do this in the css
, actually, I am not sure if this is even possible. Can I make this work in the layout.html
or in the View
somehow?
This is how I would display an image in the View
if it wasn't intended to be a background-image:
<img src="{{=URL('download', args=pic_row.pics)}}"/>
Of course, this approach to display a background-mage won't work:
<section id="main" class="main row" style="background-image:{{=URL('download', args=pic_row.pics)}}">
..but is there a way I can actually achieve this?
回答1:
<section id="main" class="main row" style="background-image:{{=URL('download', args=pic_row.pics)}}">
The above method proposed in the question is close, but the CSS syntax is incorrect. The style
attribute should be:
"background-image: url('{{=URL('download', args=pic_row.pics)}}')"
回答2:
Please read Anthony´s answer.
With this it should be possible if you include
<style>
body {
background: url('{{=URL('download',args=picture_name)}}')
}
</style>
into your view.
回答3:
Why wouldn't it work in CSS?
I'm not sure this is the best way, but surely you can construct a controller that returns an image from the database?
controllers/random.py:
def image():
image = db(db.images ...).select().first() # get the image from db
from io import StringIO
stream = StringIO(image.bytes)
response.headers['Content-Type'] = 'image/png'
return response.stream(stream, 1024**2)
And then just point your stylesheet to it.
some_view.html:
...
<style>
body { background: url("/random/image"); }
</style>
...
来源:https://stackoverflow.com/questions/30162866/how-to-change-the-background-image-using-img-file-from-database-in-web2py