微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python CGI 给了我无法单独修复的错误

如何解决Python CGI 给了我无法单独修复的错误

我有一个网页可以使用 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",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

其他注意事项: 我已经放置了文件系统标签,因为它与文件有关,例如将上传文件写入应用程序所在的文件夹。

解决方法

我修复了它,但我无法获取文件扩展名和名称。

CGI 代码:

import uuid
filename = str(uuid.uuid4())
import os 
import cgi,cgitb
form = cgi.FieldStorage()
fileitem = form.getvalue("filename")
open( "uploads/" + filename + ".bytes","wb").write(fileitem)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。