使用Django下载文件



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

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

此试验的灵感来自该线程,但我不起作用。下载一个空的TXT文件,而不是存储在服务器上的图像。在此试验代码中,确切的文件名和扩展名在路径变量中进行了硬编码。

这是您可以通过django提供文件的一种方式(尽管通常不是一个好方法,但越好的方法是使用nginx等网络服务器将文件提供服务 - 出于绩效原因 - 出于性能原因(:

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从文件扩展程序中输入content_type。https://docs.python.org/3/library/mimetypes.html

更多有关httpresponse的信息:https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.http.httpresponse

这就是为什么不建议通过django提供文件的原因,尽管不建议仅建议您可能理解自己在做什么:https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/

最新更新