无法在具有python http服务器的浏览器中查看文件

Nis*_*ara 5 python browser httpserver

我正在使用命令为远程计算机上的文件夹创建python httpserver:

python -m SimpleHTTPServer 9999
Run Code Online (Sandbox Code Playgroud)

但是我无法使用此功能在浏览器中查看文件。单击链接后,文件即被下载。有没有一种方法可以创建服务器,以便我只能在浏览器中查看文件。

Håk*_*Lid 5

要使浏览器以内联方式打开文件而不是下载它们,您必须为文件提供适当的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)
Run Code Online (Sandbox Code Playgroud)


小智 0

使用 .服务文件foo.sh应该可以正常工作 SimpleHTTPServer。作为curl客户端,我得到如下 HTTP 响应:

$ curl -v http://localhost:9999/so.sh
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9999 (#0)
> GET /so.sh HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:9999
> Accept: */*
> 
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: SimpleHTTP/0.6 Python/2.7.6
< Date: Thu, 02 Jun 2016 07:28:57 GMT
< Content-type: text/x-sh
< Content-Length: 11
< Last-Modified: Thu, 02 Jun 2016 07:27:41 GMT
< 
echo "foo"
* Closing connection 0
Run Code Online (Sandbox Code Playgroud)

您会看到标题行

Content-type: text/x-sh
Run Code Online (Sandbox Code Playgroud)

对于该文件来说这是正确的foo.sh。从文件扩展名到 的映射sh发生text/x-sh在/etc/mime.typesGNU/Linux 系统上。我的浏览器

Chromium 50.0.2661.102
Run Code Online (Sandbox Code Playgroud)

能够内联显示文件。

摘要:只要您提供已知文件并且您的浏览器可以内联显示它们,一切都应该正常。