使用python通过html <form>加载的访问文件

时间:2017-05-17 10:40:22

标签: python html forms

我有一个python脚本,它返回在浏览器中工作的html代码。 这是仅包含<form>的{​​{1}}部分的python代码:

html

在同一个python文件中发送到以下函数:

def index():
    return html("   ")


def html(woord):
    return """
<form value ='form' action=http://www.cytosine.nl/~owe4_pg3/Rogier/DreamteamPy/page1.py/fileloader method="post">
    <p>
   <LABEL for="sequence">Sequence: </LABEL>
   <INPUT type="file" name="thefile"><BR>
   <INPUT type="submit" value="Send"> <INPUT type="reset">
    </p>""" + woord+"""
</form>
"""

这样可以正常显示

def fileloader(req):
    info = req.form
    file = info["thefile"]
    woord = "<br><br>The file has been loaded:<br>{}".format(file)
    return html(woord)

在浏览器中。

但是我怎样才能真正访问该文件,例如,打印其内容? 我试过了:

The file has been loaded:
testfile.doc

但这会产生错误

def fileloader(req):
    info = req.form
    file = open(info["thefile"])
    text = file.read()
    woord = "<br><br>The file has been loaded:<br>{}".format(text)
    return html(woord)

如果我删除IOError: [Errno 2] No such file or directory: Field('thefile','testfile.doc') ,则会显示错误

open()

1 个答案:

答案 0 :(得分:0)

工作解决方案:

<form value ='form' action=http://www.cytosine.nl/~owe4_pg3/Rogier/DreamteamPy/page1.py/fileloader method="post" enctype="multipart/form-data">
    <p>
   <LABEL for="sequence">Sequence: </LABEL>
   <INPUT type="file" name="thefile"><BR>
   <INPUT type="submit" value="Send"> <INPUT type="reset">
    </p>""" + woord+"""
def fileloader(req):
    info = req.form["thefile"].file
    #file = open(info["thefile"].file)
    text = info.read()
    woord = "<br><br>The file has been loaded:<br>{}".format(text)
    return html(woord)