【发布时间】:2015-05-10 18:38:32
【问题描述】:
我正在尝试使用内置输入表单制作一个工作文件上传表单。它适用于“静态”html 输入表单(使用 shutil.copyfileobject),但无法使用内置表单。
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()
还有模板/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>
错误:
<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()
内置的 File 似乎没有返回对象,因此 shutil.copyfileobject 似乎不起作用。
请帮我整理一下。
【问题讨论】:
-
你输入了
form.Form(form.File('myfile')):你的意思是form.File('myfile')吗? -
嗯,就是这样的语法:form.Form(input form 1, input form 2)。他们根本不谈论 webpy.org 上的文件表单,我在这里找到了它:webpy.readthedocs.org/en/latest/api.html#module-web.form............ 使用您的版本呈现:文件对象不可调用
-
啊,我的错。作为第二个问题:
shutil.copy期望fi(来自fi = f['myfile'])是一个字符串(带有文件的路径)。基于this example,看起来它是一个File对象。 -
将 POST 方法编辑为:
def POST(self): f = fileForm() fi = f['myfile'] mydir = 'uploads/' oFile = open(mydir + 'name.zip', 'wb') shutil.copyfileobj(fi, oFile) oFile.close() -
Renders:
<type 'exceptions.AttributeError'> at / 'File' object has no attribute 'read'... 您发布的链接涵盖了如何在没有内置文件表单的情况下进行文件上传工作,我实际上需要使用内置文件让它工作,以避免一些丑陋的黑客攻击。
标签: python python-2.7 web web.py shutil