文件未在Django / Nginx中正常下载

时间:2013-11-22 23:02:02

标签: python django nginx

我希望用户能够从我的django网络应用程序下载文件。我编写了以下代码,但是当我下载文件时,该文件将变为错误文件。它不会打开,文件的总大小为0字节。

型号:

class Emov(models.Model):
    User=models.ForeignKey(User)
    mov_file=models.FileField(upload_to='miiv')
    mov_name=models.CharField(max_length=50)
    email=models.EmailField()   #email of the uploader
    download_count=models.PositiveIntegerField(default=0)
    #other fields follows

   @property
    def pretty_name(self):
         return "{0}.{1}".format(slugify(self.title),
                            os.path.splitext(self.mov_name.name)[1])

查看:

def document_view(request,emov_id):
    fileload=Emov.objects.get(id=emov_id)
    response=HttpResponse()
    response["Content-Disposition"]= "attachment; filename={0}".format(fileload.pretty_name)
    response['X-Accel-Redirect']="/protected/{0}".format(fileload.mov_name.name)
    return response

Nginx的

  location /protected/ {
        internal;
        root /C:/Python27/Scripts/env/Scripts/digi/media/miiv/;

}

我错过了什么?

1 个答案:

答案 0 :(得分:2)

尝试这样做:

fileload = Emov.objects.get(id=emov_id)
filename = fileload.mov_file.name.split('/')[-1]
response = HttpResponse(fileload.mov_file, content_type='text/plain') # your content type
response['Content-Disposition'] = 'attachment; filename=%s' % filename

return response

请参阅: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

希望它有所帮助。

修改
FileField.url属性您应该能够将路径传递给您的文件(例如/protected/)。 https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile