django如何从服务端下载文件到本地

2025-10-26 02:39:00

1、然后是在views.py中写好相应的response,注意这里需要反馈一个StreamingHttpResponse,而不能直接用HttpResponse

django如何从服务端下载文件到本地

2、from django.http import HttpResponse, StreamingHttpResponse

from django.core.servers.basehttp import FileWrapper

import mimetypes

import settings

import os

django如何从服务端下载文件到本地

3、def download(request):

    

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

    print (filepath)   

django如何从服务端下载文件到本地

4、    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

django如何从服务端下载文件到本地

5、接下来是在你的settings.py中设定待下载文件目录:

STATIC_URL = '/static/'  

  

django如何从服务端下载文件到本地

6、HERE = os.path.dirname(__file__)   

MEDIA_ROOT =  HERE+STATIC_URL

最后在settings.py同一目录下建一个叫static的文件夹,在里面放上你的待下载文件。

django如何从服务端下载文件到本地

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢