ملف تنزيل Django فارغ
سؤال
أكتب وظيفة بسيطة لتنزيل ملف معين ، من الخادم ، إلى الجهاز الخاص بي. الملف فريد من نوعه ممثل بمعرفه. يتم تحديد الملف بشكل عام ، ويتم التنزيل ، ولكن الملف الذي تم تنزيله (على الرغم من اسمه كسلاح على الخادم) فارغ. تبدو وظيفة التنزيل الخاصة بي مثل هذا:
def download_course(request, id):
course = Courses.objects.get(pk = id).course
path_to_file = 'root/cFolder'
filename = __file__ # Select your file here.
wrapper = FileWrapper(file(filename))
content_type = mimetypes.guess_type(filename)[0]
response = HttpResponse(wrapper, content_type = content_type)
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)
return response
أين يمكن أن أكون مخطئا؟ شكرًا!
المحلول
أجبت على هذا السؤال هنا, ، أتمنى أن يساعد ذلك.
نصائح أخرى
يبدو أنك لا ترسل أي بيانات (لا تفتح الملف).
يحتوي Django على غلاف جميل لإرسال الملفات (الرمز المأخوذ من djangosnippets.org):
def send_file(request):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
filename = __file__ # Select your file here.
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
return response
لذلك يمكنك استخدام شيء مثل response = HttpResponse(FileWrapper(file(path_to_file)), mimetype='application/force-download')
.
إذا كنت تستخدم حقًا LightTPD (بسبب "x-sendfile" رأس) ، يجب عليك التحقق من تكوين الخادم و fastcgi ، على ما أعتقد.
جرب أحد هذه النهج:
1) تعطيل gzipmiddleware إذا كنت تستخدمه ؛
2) تطبيق التصحيح على Django/core/servers/basehttp.py الموصوفة فيhttps://code.djangoproject.com/ticket/6027