要让浏览器以内联方式打开文件而不是下载文件,您必须使用适当的 http Content 标头提供文件。
使内容加载到浏览器内而不是作为下载的是标题Content-Disposition: inline
要添加这些标题,您可以将默认的SimpleHTTPRequestHandler 子类化为自定义标题。
这是使用 python 3 完成的方式。如果必须使用 python 2,则必须修改导入以及可能的其他部分。
把它放在一个可执行的脚本文件中,你可以调用 myserver.py 并像这样运行它:./myserver.py 9999
#!/usr/bin/env python3
from http.server import SimpleHTTPRequestHandler, test
import argparse
class InlineHandler(SimpleHTTPRequestHandler):
def end_headers(self):
mimetype = self.guess_type(self.path)
is_file = not self.path.endswith('/')
# This part adds extra headers for some file types.
if is_file and mimetype in ['text/plain', 'application/octet-stream']:
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Disposition', 'inline')
super().end_headers()
# The following is based on the standard library implementation
# https://github.com/python/cpython/blob/3.6/Lib/http/server.py#L1195
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
test(InlineHandler, port=args.port, bind=args.bind)