使用Django下载文件 [英] Downloading a file using Django

查看:70
本文介绍了使用Django下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中启用以前上传的文件的下载,这是到目前为止我正在使用的代码:

  def downloadview(request):
path = os.path.join('media','files','5560026113','20180412231515.jpg')
response = HttpResponse()
response ['Content-Type'] =''
response ['Content-Disposition'] =附件; filename ='Testname'
response ['X-Sendfile'] = smart_str(os .path.join(path))
返回响应

该试验的灵感来自此线程,但我无法正常工作。将下载一个空的txt文件,而不是存储在服务器上的图像。
在此试用代码中,确切的文件名和扩展名硬编码在path变量中。

解决方案

这是一种方法您可以通过Django提供文件(尽管通常这不是一种好方法,更好的方法是使用网络服务器(如nginx等)提供文件-出于性能方面的考虑):



<$来自mimetypes的p $ p> 从django中导入guess_type
.http import HttpResponse

file_path = os.path.join('media','files','5560026113 ','20180412231515.jpg')

,其中open(file_path,'rb')为f:
response = HttpResponse(f,content_type = guess_type(file_path)[0])
response ['Content-Length'] = len(response.content)
返回响应

guess_type 从文件扩展名推断content_type。
https://docs.python.org/3/library/mimetypes。 html



有关HttpResponse的更多信息,请参见: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponse



这就是为什么不建议通过Django提供文件的原因,尽管不建议这样做只是意味着您应该了解自己在做什么:
> https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/


I'm trying to enable the downloading of previously uploaded files in Django, here's the code I'm using so far:

def downloadview(request):
    path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )
    response = HttpResponse()
    response['Content-Type']=''
    response['Content-Disposition'] = "attachment; filename='Testname'"
    response['X-Sendfile']=smart_str(os.path.join(path))
    return response

The inspiration for this trial comes from this thread but I don't get it working. An empty txt file is downloaded instead of the image that is stored on the server. In this trial code the exact filename and extension is hard coded in the path variable.

解决方案

Here is a way you can serve a file through Django (although it is usually not a good approach, the better one is to serve files with a webserver like nginx etc - for performance reasons):

from mimetypes import guess_type
from django.http import HttpResponse

file_path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )

with open(file_path, 'rb') as f:
    response = HttpResponse(f, content_type=guess_type(file_path)[0])
    response['Content-Length'] = len(response.content)
    return response

guess_type infers the content_type from the file extension. https://docs.python.org/3/library/mimetypes.html

more on HttpResponse here: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponse

And here is why it is not recommended to serve files through Django, although not recommended just means that you should probably understand what you are doing: https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/

这篇关于使用Django下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆