4

ファイル オブジェクトのダウンロードを作成しようとしています。ファイルは django-filebrowser を使用して追加されました。つまり、ファイルへの文字列パスになります。私は次のことを試しました:

f = Obj.objects.get(id=obj_id)
myfile = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
...

response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'

return response

ダウンロードされるファイルには、ファイルではなく、ファイルの場所へのパスの文字列が含まれています。ファイルオブジェクトにアクセスする方法について誰か助けてもらえますか?

4

2 に答える 2

1
f = Obj.objects.get(id=obj_id)
myfile = open(os.path.join(MEDIA_ROOT, f.Audio.path)).read()
...

response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'

return response

ノート!これはメモリフレンドリーではありません!ファイル全体がメモリに入れられるため。ファイルの提供には Web サーバーを使用することをお勧めします。ファイルの提供に Django を使用する場合は、 xsendfileを使用するか、このスレッドを参照してください。

于 2012-08-07T11:57:12.950 に答える
0

ファイルを開き、そのバイナリ コンテンツを応答で送り返す必要があります。次のようなものです:

fileObject = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
myfile = open(fileObject.path)
response = HttpResponse(myfile.read(), mimetype="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response

あなたが探しているものが得られることを願っています。

于 2012-08-07T11:56:10.083 に答える