簡體   English   中英

使用內置文件格式上傳web.py文件

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

我正在嘗試使用內置的輸入表單制作一個工作文件上傳表單。 它與“靜態” 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()

還有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>

錯誤:

<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似乎不起作用。

請幫我整理一下。

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