处理从python中的html表单上传文件

时间:2013-08-12 22:55:28

标签: python html forms file-upload cgi

我有一个简单的html表单和后端python由cgi-bin处理。我试图通过表单上传文件,并在我的python脚本中打印该文件的内容。 我的HTML代码:

<form id = "upload" enctype="multipart/form-data" action="/var/www/cgi-bin/test.py" method="post">
            <div id = "table">
                <table class = "center" border="1" cellpadding="10">
                    <tr><td style="height: 131px">Product Details</td>
                        <td style="height: 131px">Product Name*:&nbsp;<input type="text"  name="product" id="product" size="35" ><br /><br />
                                                  Platform*: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   <input type="text"  name="platform" id="platform" size="35" >
                    </td></tr> 
                    <tr><td style="height: 131px">File Upload</td>
                    <td style="height: 131px"><p>Upload Host File: <input type="file" name="hostupload" /></p><br/>
                                                 Upload Test File: <input type="file" name="testupload" /></p>
                    </td></tr> 
                    <tr align="center"><td></td><td><input type = "submit" id="upload" value = "UPLOAD"/>
                   </td></tr>   
                </table>
            </div>
        </form>

我的python代码:

#!/usr/local/bin/python
import os
import commands
import cgi, cgitb

print "Content-Type: application/json"
print
form = cgi.FieldStorage()


product = form['product'].value
platform =  form['platform'].value
filedata = form['hostupload']
print product
print platform

if filedata.file:
   print filedata.file.read()

产品和平台打印正常。但如果我添加行filedata = form ['hostupload'],我收到错误:

File "/usr/local/lib/python2.7/cgi.py", line 541, in __getitem__, referer:   
[error] [client 10.1.1.212]     raise KeyError, key,  

但名称“hostupload”在我的表单中是正确的。谁能告诉我哪里出错了?

0 个答案:

没有答案