Djangoダウンロードファイルが空です
質問
サーバーからマシンまで、特定のファイルをダウンロードするための簡単な機能を作成しています。ファイルはIDで表される一意です。ファイルはcorctdでlocatdであり、ダウンロードは完了しますが、ダウンロードされたファイル(サーバー上のものと呼ばれていますが)は空です。私のダウンロード機能は次のようになります:
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つを試してください。
1)Gzipmiddlewareを使用している場合は無効にします。
2)django/core/servers/basehttp.pyにパッチを適用します。https://code.djangoproject.com/ticket/6027
所属していません StackOverflow