简体   繁体   中英

python cgi PermissionError: [Errno 13] Permission denied:

on my macOS, I try to use apache and python cgi to build a very simple web site, where I can upload an image and then output if I succeed or fail. Here is the 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>

Here is the hello.py where I write the python cgi part:

#!/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,))

In fact, I copy most of the code from http://cgi.tutorial.codepoint.net/file-upload , I have also run chmod 755 hello.py to deal with the permission. However, after I upload a image called "123.png" and click upload button, a error occurs:

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'

And I don't know why. In fact, I don't even understand what is "open('files/'+fn,'wb').write(fileitem.file.read())" used for. But if I delete this line, it will give me a blank page. Please give some advices, thanks!

The line you mention takes the content of uploaded file and writes it to the server directory with the original filename given by web user.

The error has nothing to do with hello.py permissions, in order to fix it you need to make sure files directory exists and has write permission.

However, most likely you need to specify more accurate file / directory names for uploaded file area (for example original web user file name is not the best idea) and add the appropriate write permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM