您的位置:首页 > 编程语言 > Go语言

django服务器提供下载文件

2013-12-31 04:54 495 查看
参考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/

下载成功:)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: