我希望用户能够从我的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/;
}
我错过了什么?
答案 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
希望它有所帮助。
修改强>:
FileField.url
属性您应该能够将路径传递给您的文件(例如/protected/
)。 https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile