我想设计一个简单的站点,一个人可以在其中上传文件,然后将随机网址传递给某人,然后某人可以下载它。
此时,我有一个网页,有人可以在其中成功上传存储在我的网络服务器上/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/