Home  >  Q&A  >  body text

[Problem with Python uploading files] When uploading files according to online tutorials, 500 errors keep appearing.

Follow the tutorial on the Internet and use Python to write CGI to upload files, but 500 keeps appearing. What's going on?

html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form enctype="multipart/form-data" action="save_file.py" method="post">
        <p>
            选中文件: <input type="file" name="filename" />
        </p>
        <p>
            <input type="submit" value="上传"/>
        </p>
    </form>
</body>
</html>

.py file

#!/usr/bin/python
# -*- coding:utf-8 -*-

import cgi, os
import cgitb; cgitb.enable()

# 获取文件名
f = cgi.FiledStorage().getvalue('filename')

# 检测文件是否上传
if f is not  None:
    # 设置文件路径
    fn = os.path.basename(f.filename.replace("","/"))
    open('/tmp/' + fn,'wb').write(f.file.read())

    message = '文件 "' + fn + '" 上传成功'

else:
    message = "文件没有上传"

print """
    Content-Type:text/html
    <html>
        <head>
            <meta charset="utf-8">
            <title>文件上传</title>
        </head>
        <body>
            <p> %s </p>
        </body>
    </html>
""" % (message,)

error message:

[Thu May 11 10:24:46.697197 2017] [http:error] [pid 8254] [client 127.0.0.1:58072] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://studycgi/file/file.html

127.0.0.1 - - [11/May/2017:10:24:41 +0800] "POST /file/save_file.py HTTP/1.1" 500 4063
大家讲道理大家讲道理2711 days ago899

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-18 10:51:26

    Don’t you think the URL in your error message looks weird? Open it in your browser and take a look.

    Shouldn’t it be studycgi.com

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-18 10:51:26

    Isn’t the error message relatively clear: Response header name '<!--' contains invalid characters

    reply
    0
  • Cancelreply