我试图让用户上传图像,将图像保存到磁盘,然后将其显示在网页上,但我无法正常显示图像。这是我的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。它会查找prgram所在的目录。现在,在html中,你可以使用
<img src="/image/"+$datafile alt="your picture">
我建议使用或使用“imageBinary = open(”{...“行)。
如果需要更多信息,请与我们联系。这是我的第一反应。
很抱歉在回复中提出问题,但有没有办法使用正则表达式,如(.jpg)代替我在URL定义中的(。)?
web.py不会自动提供运行应用程序的目录中的所有文件 - 如果有的话,任何人都可以读取应用程序的源代码。但是,它有一个目录,它提供以下文件:static
。
回答你的另一个问题:是的,有一种方法可以避免使用绝对路径:给它一个相对路径!
以下是您的代码之后的外观:
filename = form.datafile.filename.replace('\\', '/').split('/')[-1]
# It might be a good idea to sanitize filename further.
# A with statement ensures that the file will be closed even if an exception is
# thrown.
with open(os.path.join('static', filename), 'wb') as f:
# shutil.copyfileobj copies the file in chunks, so it will still work if the
# file is too large to fit into memory
shutil.copyfileobj(form.datafile.file, f)
省略filename = filedir + "/" + filename
线。您的模板不需要包含绝对路径:事实上,它不应该包含;你必须包括static/
;不多也不少:
<img src="static/$datafile" alt="your picture">