【发布时间】:2021-01-30 17:39:48
【问题描述】:
我有一个网页可以使用 CGI 将文件上传到我的 python 服务器,但是当我提交文件时,它给了我这个错误。
::1 - - [30/Jan/2021 18:30:40] b'Traceback (most recent call last):\r\n File "C:\\Users\\user\\Desktop\\upload file\\cgi-bin\\python_script.py", line 8, in <module>\r\n if fileitem.getvalue("filename"): \r\nAttributeError: \'bytes\' object has no attribute \'getvalue\'\r\n'
::1 - - [30/Jan/2021 18:30:40] CGI script exit status 0x1
HTML 代码:
<html>
<body>
<form enctype = "multipart/form-data" action = "cgi-bin/python_script.py" method = "post">
<p>Upload File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
CGI 代码:
import os
import cgi, cgitb
form = cgi.FieldStorage()
fileitem = form.getvalue("filename")
# check if the file has been uploaded
if fileitem.getvalue("filename"):
fn = os.path.basename(fileitem.filename)
#read and write file into server
open(fn, 'wb').write(fileitem.getvalue("file").read())
我不知道如何解决这个问题,我在一些代码中添加了 getvalue(),但我的错误没有得到解决
完整的服务器日志:
Serving HTTP on :: port 8080 (http://[::]:8080/) ...
::1 - - [30/Jan/2021 18:30:10] "GET / HTTP/1.1" 304 -
::1 - - [30/Jan/2021 18:30:39] "POST /cgi-bin/python_script.py HTTP/1.1" 200 -
::1 - - [30/Jan/2021 18:30:39] command: C:\Users\user\AppData\Local\Programs\Python\Python39\python.exe -u "C:\Users\ETORE\Desktop\upload file\cgi-bin\python_script.py" ""
::1 - - [30/Jan/2021 18:30:40] b'Traceback (most recent call last):\r\n File "C:\\Users\\user\\Desktop\\upload file\\cgi-bin\\python_script.py", line 8, in <module>\r\n if fileitem.getvalue("filename"): \r\nAttributeError: \'bytes\' object has no attribute \'getvalue\'\r\n'
::1 - - [30/Jan/2021 18:30:40] CGI script exit status 0x1
其他说明: 我已经放置了文件系统标签,因为它与文件有关,例如将上传的文件写入应用程序所在的文件夹。
【问题讨论】:
-
正如错误告诉你的那样,
fileitem是一个类型为bytes的对象,该对象类型没有名为getvalue的属性/方法 -
嗯,如果我删除 if 语句并在 after 代码上获取值,那么它将起作用。
标签: python forms post filesystems cgi