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)