注意
如果运行不起来,可以修改引用路径
print后的空格去掉
chmod 755 fileName.py
HTML设置上传文件的表单需要设置 enctype 属性为 multipart/form-data,代码如下所示:
菜鸟教程(runoob.com)action="/cgi-bin/save_file.py" method="post">
选中文件:
save_file.py脚本文件代码如下:
#!/usr/bin/python3
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# 获取文件名
fileitem = form['filename']
# 检测文件是否上传
if fileitem.filename:
# 设置文件路径
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
fp = os.path.abspath(fn)
message = '文件 "' + fn + '" 上传成功'
else:
message = '文件没有上传'
print ("""\
Content-Type: text/html\n
菜鸟教程(runoob.com)%s
filePath:%s
""" % (message,fp![![屏幕快照 2018-11-26 下午5.55.34.png](https://upload-images.jianshu.io/upload_images/5584267-80dda7f4c5e14862.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://upload-images.jianshu.io/upload_images/5584267-a2a72b1d2037396e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
,))
将以上代码保存到 save_file.py,并修改 save_file.py 权限:
chmod 755 save_file.py
效果
save_file_html.png
save_file_py.png
如果你使用的系统是Unix/Linux,你必须替换文件分隔符,在window下只需要使用open()语句即可:
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))