【问题标题】:Reading a file uploaded via CGI in Python在 Python 中读取通过 CGI 上传的文件
【发布时间】:2012-10-27 20:37:39
【问题描述】:

我在分析上传到我的服务器的文件时遇到问题。理想情况下,用户会上传一个 .csv,我会从文件中的数据运行一些数字积分(因此是 import numpy as np)并返回结果。为了在进行任何分析之前测试 cgi 部分,我制作了下面的 python 脚本。我的问题是消息总是显示为空白,所以最后我在浏览器中显示了一个空白的 html 页面。

显然我没有正确读取文件(这意味着我无法分析它),但我不知道我做错了什么。我自己的搜索表明我下面的内容应该可以工作。

#!/usr/bin/python

#---------------------------------------------
#=============================================
#---------------------------------------------
#imports

#import csv
#import time as tm
#import numpy as np
#import os
import cgi, cgitb

cgitb.enable()

form = cgi.FieldStorage()

#The variables
#httpopen=""
#httpclose=""
message="meow"

#get the fileitem
fileitem=form['userfile']
if fileitem.file:
    #yay...we got a file
    message=fileitem.file.readline()


print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)

这是提供上传的 html 表单:

<html>
<body>
   <form enctype="multipart/form-data" 
                     action="capacity_rewrite.py" method="post">
   <p>File: <input type="file" name="userfile" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>
</body>
</html>

谢谢,

【问题讨论】:

    标签: python upload cgi


    【解决方案1】:

    您只从上传的文件中读取一行。也许第一行是空行?改用fileitem.file.read(),它将把整个文件读入一个字符串。不要对大文件执行此操作,因为您可能会耗尽内存,但这应该有助于理解您的测试。

    【讨论】:

    • 就是这样。我觉得自己像个彻头彻尾的白痴。该文件不应该有一个空行,所以我只是假设它是我期望的格式。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2010-10-20
    • 2017-03-09
    • 2014-07-06
    • 2017-10-26
    • 1970-01-01
    • 2013-09-04
    相关资源
    最近更新 更多