django服務器提供下載文件

參考http://blog.csdn.net/wildcatlele/article/details/12146147 在這篇文章的基礎上做了些許修改,因爲按照原文章的做法會在我的環境下(python 2.7.6)下報錯。

首先是配置url,在urls.py中配置好你的下載地址及response:

from GardeServeur.views import update, download

url(r'^garde/download/$',download),


然後是在views.py中寫好相應的response,注意這裏需要反饋一個StreamingHttpResponse,而不能直接用HttpResponse

from django.http import HttpResponse, StreamingHttpResponse

from django.core.servers.basehttp import FileWrapper

import mimetypes

import settings

import os


def download(request):

    

    filepath = os.path.join(settings.MEDIA_ROOT, "new.apk");

    print (filepath)   

    wrapper = FileWrapper(open(filepath, 'rb'))  

    content_type = mimetypes.guess_type(filepath)[0]  

    response = StreamingHttpResponse(wrapper, 'content_type')  

    response['Content-Disposition'] = 'attachment; filename="new.apk"' 

    return response


接下來是在你的settings.py中設定待下載文件目錄:

STATIC_URL = '/static/'  

  

HERE = os.path.dirname(__file__)   

MEDIA_ROOT =  HERE+STATIC_URL


最後在settings.py同一目錄下建一個叫static的文件夾,在裏面放上你的待下載文件。


正如你所見,我的下載地址是;http://192.168.1.103:8000/garde/download/

下載成功:)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章