[英]Reading a file uploaded via CGI in Python
I am having trouble analyzing a file that is uploaded to my server. 我在分析上传到我的服务器的文件时遇到问题。 Ideally, what would happen is that the user would upload a .csv and I would run some numeric integration (hence the import numpy as np
) from data in the file and return the result. 理想情况下,用户会上传.csv,我会从文件中的数据运行一些数字集成(因此import numpy as np
)并返回结果。 To test the cgi part before I did any analysis, I made the python script below. 为了在进行任何分析之前测试cgi部分,我在下面制作了python脚本。 My problem is that message always appears blank, so I get a blank html page displayed in browser at the end. 我的问题是消息总是显示为空白,所以我得到一个空白的html页面,最后显示在浏览器中。
Clearly I am not reading the file correctly (which means I can not analyze it), but I have no idea what I am doing wrong. 显然我没有正确读取文件(这意味着我无法分析它),但我不知道我做错了什么。 My own searches indicate that what I have below should work. 我自己的搜索表明我下面的内容应该有效。
#!/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,)
And here is the html form that gives the upload: 以下是提供上传的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>
Thanks, 谢谢,
You're only reading one line from the uploaded file. 您只是从上传的文件中读取一行。 Perhaps that first line is a blank line? 或许第一行是一个空白行? Try fileitem.file.read()
instead, which will read the entire file into a string. 请尝试使用fileitem.file.read()
,它会将整个文件读入字符串。 Don't do that for large files as you may run out of memory, but it should help in understanding your test. 不要为大文件这样做,因为你可能会耗尽内存,但它应该有助于理解你的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.