简体   繁体   English

使用内置文件格式上传web.py文件

[英]web.py file upload using the built in File form

I'm trying to make a working file upload form using the built in input form. 我正在尝试使用内置的输入表单制作一个工作文件上传表单。 It works just fine with a 'static' html input form (using shutil.copyfileobject), but it won't work using the built in one. 它与“静态” html输入表单(使用shutil.copyfileobject)配合使用时效果很好,但无法使用内置的html输入表单。

import web, shutil
from web import form

urls = ('/', 'Index')

app = web.application(urls, globals())
render = web.template.render('templates/')

fileForm = form.Form(form.File('myfile'))

class Index(object):
    def GET(self):
        f = fileForm()
        return render.index(f)
    def POST(self):
        f = fileForm()
        fi = f['myfile']
        mydir = 'uploads/'
        shutil.copy(fi, mydir)

if __name__ == "__main__":
    app.run()

And templates/index.html 还有template / index.html

$def with (f)
<!DOCTYPE html>
<html>

<head> 

<title>Title</title>

</head>

<body>
<form name="main" method="post" enctype="multipart/form-data" action="">
$:f.render()
<input type="submit">
</form>
</body>

</html>

Errors: 错误:

<type 'exceptions.TypeError'> at /

coercing to Unicode: need string or buffer, File found


Python
C:\Python27\lib\ntpath.py in abspath, line 486 

Web
POST http://localhost:8080/ 


Traceback (innermost first)
C:\Python27\lib\ntpath.py in abspath 
479.
480.else:  # use native Windows method on Windows
481.    def abspath(path):
482.        """Return the absolute version of a path."""
483.
484.        if path: # Empty path must return current working directory.
485.            try:
486.                path = _getfullpathname(path) ...
487.            except WindowsError:
488.                pass # Bad path - return unchanged.
489.        elif isinstance(path, unicode):
490.            path = os.getcwdu()
491.        else:
492.            path = os.getcwd()

The built in File doesn't seem to return an object, so shutil.copyfileobject does not seem to work. 内置的File似乎没有返回对象,因此shutil.copyfileobject似乎不起作用。

Please help me sort it out. 请帮我整理一下。

import web, shutil
from web import form

urls = ('/', 'Index')

app = web.application(urls, globals())
render = web.template.render('templates/')

fileForm = form.Form(form.File('myfile'))

class Index(object):
    def GET(self):
        f = fileForm()
        return render.index(f)

    def POST(self):
        x = web.input(myfile={})
        filedir = '/tmp/'
        if 'myfile' in x:
            filepath=x.myfile.filename.replace('\\','/')
            filename=filepath.split('/')[-1]
            fout = open(filedir +'/'+ filename,'w')
            fout.write(x.myfile.file.read())
            fout.close()

if __name__ == "__main__":
    app.run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM