python cgi PermissionError: [Errno 13] Permission denied:

python cgi PermissionError: [Errno 13] Permission denied:

在我的 macOS 上,我尝试使用 apache 和 python cgi 构建一个非常简单的网站,我可以在其中上传图像,然后在成功或失败时输出。这是 index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>upload</title>
    </head>
<body>
<form enctype="multipart/form-data" action="/CGI-Executables/hello.py" method="post">
<p>upload:<input type="file" name="filename" /></p>
<p><input type="submit" value="upload" /> </p>
</form>
</body>
</html>

这里是 hello.py 我写 python cgi 部分的地方:

#!/anaconda3/bin/python
# -*- coding: UTF-8 -*-
print ('Content-Type: text/html')
print ('')
import cgi,os
import cgitb;cgitb.enable()
form=cgi.FieldStorage()
fileitem=form['filename']

if fileitem.filename:
    fn=os.path.basename(fileitem.filename)
    open('files/'+fn,'wb').write(fileitem.file.read())
    message = "successful"
else:
    message='fail'
    print ("""\
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,))

其实大部分代码我都是从http://cgi.tutorial.codepoint.net/file-upload复制过来的,我也有运行 chmod 755 hello.py来处理权限。但是,在我上传名为“123.png”的图片并单击上传按钮后,出现错误:

Traceback (most recent call last):
  File "/Users/chuci/apa/CGI-Executables/hello.py", line 12, in <module>
    open('files/'+fn,'wb').write(fileitem.file.read())
PermissionError: [Errno 13] Permission denied: 'files/123.png'

我也不知道为什么。事实上,我什至不明白"open('files/'+fn,'wb').write(fileitem.file.read())"是做什么用的。但是如果我删除这一行,它会给我一个空白页。请多多指教,谢谢!

您提到的那行获取上传文件的内容,并使用网络用户提供的原始文件名将其写入服务器目录。

该错误与 hello.py 权限无关,要修复它,您需要确保 files 目录存在并且具有写入权限。

但是,很可能您需要为上传的文件区域指定更准确的文件/目录名称(例如原始网络用户文件名不是最好的主意)并添加适当的写入权限。