首页 > 代码库 > web.py文件上传

web.py文件上传

程序如下:

import webimport cgicgi.maxlen = 10 * 1024 * 1024 # 10MB#http://192.168.2.125:8080/uploadurls = (/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

效果:

 

目录结构:

启动过程:

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文件上传