我试图让用户上传图像,将图像保存到磁盘,然后将其显示在网页上,但我无法使图像正常显示。这是我的 bin/app.py
:
import web
urls = (
'/hello', 'index'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
class index:
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(greet="Hello", name="Nobody", datafile={})
greeting = "%s, %s" % (form.greet, form.name)
filedir = 'absolute/path/to/directory'
filename = None
if form.datafile:
# replaces the windows-style slashes with linux ones.
filepath = form.datafile.filename.replace('\\','/')
# splits the and chooses the last part (the filename with extension)
filename = filepath.split('/')[-1]
# creates the file where the uploaded file should be stored
fout = open(filedir +'/'+ filename,'w')
# writes the uploaded file to the newly created file.
fout.write(form.datafile.file.read())
# closes the file, upload complete.
fout.close()
filename = filedir + "/" + filename
return render.index(greeting, filename)
if __name__ == "__main__":
app.run()
这里是templates/index.html
:
$def with (greeting, datafile)
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>
$else:
<em>Hello</em>, world!
<br>
$if datafile:
<img src=$datafile alt="your picture">
<br>
<a href="/hello">Go Back</a>
当我这样做时,我得到了一个损坏的图像链接。如何让图像正常显示?理想情况下,我不必从磁盘读取来显示它,尽管我不确定这是否可能。另外,有没有办法将文件写入相对路径,而不是绝对路径?
最佳答案
您还可以通过向 URL 添加条目来插入文件夹中所有图像的路径。
URL = ('/hello','Index',
'/hello/image/(.*)','ImageDisplay'
)
...
class ImageDisplay(object):
def GET(self,fileName):
imageBinary = open("/relative/path/from/YourApp}"+fileName,'rb').read()
return imageBinary
不是 ../YourApp,不是 ./YourApp。它从您的程序所在的目录中查找一个目录。现在,在 html 中,您可以使用
<img src="/image/"+$datafile alt="your picture">
我建议使用或尝试使用 "imageBinary = open("{..."行。
如果需要更多信息,请告诉我。这是我的第一 react 。
很抱歉在回复中提出问题,但是有没有办法使用正则表达式,比如 (.jpg) 代替我在 URL 定义中的 (.)?
关于python - 如何使用 web.py 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417221/