python - 在 Python 中读取通过 CGI 上传的文件

标签 python upload cgi

我在分析上传到我的服务器的文件时遇到问题。理想情况下,用户会上传一个 .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>

谢谢,

最佳答案

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

关于python - 在 Python 中读取通过 CGI 上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275657/

相关文章:

php - 如何在 mysql 表中自动链接上传

ruby - 寻找一个简单的 ruby​​ 模板解决方案

python - 我可以将 python 的 `for` 语句与这样的 SQL 结合起来吗 : `for id, name, ctime in db.select(' table_name', where ='...' )`

python - 日期转换器

ajax - 如何使用 AJAX 从 Phonegap 移动应用程序上传图片?

java - 是什么原因导致这个 ajax-upload javascript 错误?

python - MongoDB Python 和 C++ 客户端 - 多个实例出错

python - MySQL 对不在类 GPL 许可下的 Python 的支持

作为 Apache CGI 程序运行的 C++ 程序无法通过 shmget 访问共享内存

security - 基于 CGI 的 Web 应用程序的安全性如何?