从django下载的文件没有文件扩展名

时间:2013-12-27 20:22:57

标签: django

我在我的Django 1.5 progect上写了一个视图,让用户下载文件。

这是代码:

import mimetypes
from django.http import HttpResponse

def filedownload(request, file_name):
    down_file = File.objects.get(name = file_name)
    file_path = MEDIA_ROOT+str(down_file.file) #down_file.file is something like folder/name_file.extension
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % file_name
    response['X-Sendfile'] = file_path
    return response

它工作正常,但文件是在没有扩展名的情况下下载的。为什么?我怎么解决这个问题?我知道我可以让网络服务器执行此操作,但这是一个虚拟项目,只能在Django中工作。

编辑: 我解决了谢谢sk1p的答案并使用更精细的代码here

1 个答案:

答案 0 :(得分:3)

您正在使用以下行指定要在浏览器中显示的文件名:

response['Content-Disposition'] = 'attachment; filename=%s' % file_name

因此如果file_name不包含扩展名,则下载也不会。所以:确保Content-Disposition标题包含正确的文件名和扩展名!

相关问题