2010-05-24 63 views
3

我想設計一個簡單的網站,一個人可以上傳一個文件,然後將隨機的網絡地址傳遞給某個人,然後他可以下載它。Python中的文件共享網站

此時,我有一個網頁,有人可以成功上傳一個文件,該文件存儲在我的網絡服務器的/ files /下。

的Python腳本還生成被存儲在數據庫中識別文件

我已經找回叫另一頁,其中一個人應該去,放在5字母代碼一個獨特的,隨機的5字母代碼,以及它應該彈出一個文件夾詢問文件的保存位置。

我的問題是:1)如何檢索文件以供下載?在這一點上我的檢索腳本,獲取代碼,獲取我的服務器上的文件的位置,但我如何讓瀏覽器開始下載?

2)如何阻止人們直接進入文件?我應該更改文件權限嗎?

+2

這有點偏離主題,但你可能要生成一個散列(如SHA1)和使用該代替5個字母的代碼進行存儲。這樣可以防止重複輸入同一個文件,也是一種更強大的身份驗證方法。 – alternative 2010-05-24 21:47:00

回答

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() 
+0

感謝您的回覆。正如我剛剛開始學習python,我真的不明白這一點。 我在我的機器上本地運行了這段代碼,用a5.pdf替換test.py並去到了網址127.0.0.1:8080。腳本提示下載文件,但下載了擴展名爲.dmz.part的文件。我如何獲得它下載整個文件? 你能指點我一個關於主題的好教程嗎? – Ali 2010-05-25 23:14:51

0

您應該發送正確的HTTP響應,其中包含二進制數據並使瀏覽器對其作出反應。

試試這個(我沒有),如果你使用Django:

response = HttpResponse() 
response['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, file.file.path) 
content_type, encoding = mimetypes.guess_type(file.file.read())    
if not content_type: 
    content_type = 'application/octet-stream'    
response['Content-Type'] = content_type    
response['Content-Length'] = file.file.size    
response['Content-Disposition'] = 'attachment; filename="%s"' % file.file.name 
return response 

來源:http://www.chicagodjango.com/blog/permission-based-file-serving/

+0

感謝您的回覆。我真的沒有啓動django,所以不能說這是否會起作用。你能不能指點我一個關於主題的好教程?將urllib.urlretrieve幫助? – Ali 2010-05-25 23:19:43

+0

你使用什麼web框架? – 2010-05-26 07:49:04