python - Python 中的文件共享站点

标签 python file-upload cgi

我想设计一个简单的站点,一个人可以在其中上传文件,然后将随机网址传递给某人,然后某人可以下载它。

此时,我有一个网页,有人可以在其中成功上传存储在我的网络服务器上/files/下的文件。

python 脚本还会生成一个唯一的随机 5 字母代码,该代码存储在数据库中以标识该文件

我有另一个名为 retrieve 的页面,一个人应该去哪里,输入 5 个字母的代码,它应该弹出一个文件框,询问将文件保存到哪里。

我的问题是:1) 如何检索要下载的文件?此时我的检索脚本获取代码,获取文件在我的服务器上的位置,但如何让浏览器开始下载?

2) 如何阻止人们直接访问文件?我应该更改文件的权限吗?

最佳答案

您如何提供文件上传页面,以及如何让您的用户上传文件?
如果您使用的是 Python 的内置 HTTP 服务器模块,则应该没有任何问题。
无论如何,这里是文件服务部分是如何使用 Python 的内置模块完成的(只是基本思想)。

关于你的第二个问题,如果你一开始就使用这些模块,你可能不会问它,因为你必须明确提供特定文件。

import SocketServer
import BaseHTTPServer


class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        # The URL the client requested
        print self.path

        # analyze self.path, map the local file location...

        # open the file, load the data
        with open('test.py') as f: data = f.read()

        # send the headers
        self.send_response(200)
        self.send_header('Content-type', 'application/octet-stream') # you may change the content type
        self.end_headers()
        # If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.

        # wfile is a file-like object. writing data to it will send it to the client
        self.wfile.write(data)

        # XXX: Obviously, you might want to send the file in segments instead of loading it as a whole


if __name__ == '__main__':

    PORT = 8080 # XXX

    try:
        server = SocketServer.ThreadingTCPServer(('', 8080), RequestHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

关于python - Python 中的文件共享站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2900514/

相关文章:

python - 如何将python脚本作为linux命令运行

python - 如何解压 Pandas 数据框中的列表列

python - Pika blocking_connection.py 随机超时连接到 RabbitMQ

javascript - 文件输入转换按钮转换为 Angular 中带有文件名的上传按钮

python - cgi 脚本无法在浏览器中正确呈现

python - 使用 python 从 csv 数据集中消除不存在/空值

java - 通过流式传输将分段文件上传到 Amazon S3 时内存使用率过高?

jquery - 如何在 ASP.NET MVC 中处理 HTML5 多文件上传?

javascript - 获取我的页面开始运行 angularjs 的时间

web-applications - 这些天使用的 CGI 脚本是什么?