简体   繁体   English

如何下载使用django-filebrowser上传的文件?

[英]How to download a file uploaded using django-filebrowser?

I am trying to create a download of a file object. 我正在尝试创建一个文件对象的下载。 the file was added using django-filebrowser which means it is turn in to a string path to the the file. 该文件是使用django-filebrowser添加的,这意味着它将转入该文件的字符串路径。 I have tried the following: 我尝试过以下方法:

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

The file that is downloaded contains the string of the path to the file location and not the file. 下载的文件包含文件位置的路径字符串,而不是文件。 Could anyone be of assistance on how to access the file object? 任何人都可以帮助如何访问文件对象?

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

NOTE! 注意! This is not memory friendly! 这不是内存友好的! Since the whole file is put into memory. 由于整个文件被放入内存。 You're better of using a webserver for file serving or if you want to use Django for file serving you could use xsendfile or have a look at this thread 您最好使用Web服务器进行文件服务,或者如果您想使用Django进行文件服务,可以使用xsendfile或查看此主题

You need to open the file and send it's binary contents back in the response. 您需要打开文件并将其二进制内容发送回响应中。 So something like: 所以类似于:

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

Hope that gets what you're looking for. 希望得到你想要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM