码迷,mamicode.com
首页 > Web开发 > 详细

web.py文件上传

时间:2014-09-02 12:18:24      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   文件   2014   

程序如下:

bubuko.com,布布扣
import web
import cgi

cgi.maxlen = 10 * 1024 * 1024 # 10MB
#http://192.168.2.125:8080/upload
urls = (/upload, upload)

render = web.template.render(templates/)

fmap = {
  "f1": "/tmp/upload1",
  "f2": "/tmp/upload2"
}



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


    def POST(self):
        try:
            x = web.input(myfile={})
            #web.debug(x[myfile].filename)
            #web.debug(x[myfile].value)
            #web.debug(x[myfile].file.read())
            #filedir = /root/python/web.py-0.33/uploadfile # /home/zcw/python/web_chanelpack/web.py-0.33/uploadfile2
            if myfile in x: # to check if the file-object is created
                filepath=x.myfile.filename.replace(\\,/) # replaces the windows-style slashes with linux ones.
                filename=filepath.split(/)[-1] # splits the and chooses the last part (the filename with extension)
                
                fid = web.input(fid="").fid
                fpath = fmap[fid]
                print "fpath: %s" % fpath

                fout = open(fpath +/+ filename,w) # 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.
            raise web.seeother(/upload?fid=%s % fid)
        except ValueError:
            return "File too large"


if __name__ == "__main__":
   app = web.application(urls, globals()) 
   app.run()
View Code

效果:

bubuko.com,布布扣

 

目录结构:

bubuko.com,布布扣

启动过程:

sudo python setup.py install
sudo python upload.py 5987 &
访问:http://127.0.0.1:5987/upload?fid=f2

 web.py下载地址:http://webpy.org/static/web.py-0.33.tar.gz

web.py文件上传

标签:style   blog   http   color   os   io   ar   文件   2014   

原文地址:http://www.cnblogs.com/super-d2/p/3951085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!