2

我试图让用户上传图像,将图像保存到磁盘,然后将其显示在网页上,但我无法正确显示图像。这是我的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>  

当我这样做时,我得到一个损坏的图像链接。如何让图像正确显示?理想情况下,我不必从磁盘读取来显示它,尽管我不确定这是否可能。另外,有没有办法将文件写入相对路径,而不是绝对路径?

4

2 回答 2

1

您还可以通过向 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 定义中的 (.)?

于 2014-12-03T04:02:55.383 回答
0

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">
于 2013-07-02T04:28:56.990 回答