【问题标题】:How to do multiple files upload on webpage and save on disk in web.py?如何在网页上上传多个文件并在 web.py 中保存在磁盘上?
【发布时间】:2016-05-20 07:30:27
【问题描述】:

我正在关注 Zed shaw http://learnpythonthehardway.org/book/ex51.html 的 LPTHW ex51,并且正在 web.py 上进行他的学习练习,我是 web.py 初学者,并且成功地在网页表单上上传图像,然后将其存储在本地文件夹。问题是我存储的每张图片都替换了之前的一张。我也不知道如何在服务器上上传多个图像并将它们全部存储。

这是我在 app.py 中上传的课程:

class Upload(object):
    def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        return render.upload()

    def POST(self):
        x= web.input(myfile={})
        filedir= "C:/Users/tejas/Documents/filesave"
        if 'myfile' in x:
            fout = open(filedir + '/' + 'myfile.jpg', 'wb') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete
            return "Success! Your image has been saved in the given folder."
            raise web.seeother('/upload')

还有我的上传表单-upload.html:

<html>
    <head><title>

    <div id="header" <h1 style="color:blue;">Upload image file</h1><div/>

    </title></head>

    <body background-color=light-blue,font-family=verdana,font-size=100%;>
        <form method="POST" enctype="multipart/form-data" action="">
        <input type="file" name="myfile"/>

     <br/> <br/><br/>
        <input type="submit"/>
        </form>
        </body>
        </html>

我尝试了很多类似的问题,但都是在 PHP 中,所以我尝试了与代码类似的东西,但我无法让它工作。有什么改进代码的建议吗?

【问题讨论】:

    标签: python-2.7 web.py


    【解决方案1】:

    您的代码替换早期代码的原因是您对保存图像的路径进行了硬编码

    fout = open(filedir + '/' + 'myfile.jpg', 'wb')
    

    每次您上传要更改的文件都是一样的,这可以通过每次上传新文件时添加一个新名称或从网络输入中提取名称来纠正

    fout = open(filedir + '/' + x.myfile.filename, 'wb');
    

    根据python打开写入同名文件时会被擦除 确保您上传的每个新文件的名称都与之前上传的不同

    【讨论】:

    • 感谢 很高兴能提供帮助
    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    相关资源
    最近更新 更多