在移动浏览器上强制下载Django Web App中的文件

时间:2023-02-06 00:28:54

I have a FileField with a movie, I'm trying to have the user on a mobile platform (chrome/safari) be able to click a download button and it download it. Currently it opens in a new window no matter what I do.

我有一个带有电影的FileField,我试图让用户在移动平台(chrome / safari)上点击下载按钮然后下载它。目前,无论我做什么,它都会在新窗口中打开。

My View

def download(request):
    file_path = 'movie.mp4'
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="video/mp4")
            response['Content-Disposition: attachment'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

file path is hard coded for testing purposes atm.

文件路径是硬编码的,用于测试目的atm。

Everything I read tells me that it's impossible because safari and other mobile browsers view opening a better experience than downloading. I've tried changing mime types and other things.

我读到的所有内容都告诉我,这是不可能的,因为safari和其他移动浏览器可以看到打开比下载更好的体验。我试过改变mime类型和其他东西。

2 个解决方案

#1


0  

Your content-disposition must containattachment to allow the user to download it, it should be something like this:

您的内容处置必须包含允许用户下载的附件,它应该是这样的:

response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) + '.mp4'

#2


0  

I don't know a lot about python but I saw that you have only one reaction so I have done my bit of research and this is what I found. Click link open in other window need same I know it's not a download but a download is always a way of using a link.
Maybe you are able to combine those codes and make it work.

我不太了解python,但我看到你只有一个反应,所以我做了一些研究,这就是我发现的。点击其他窗口中打开的链接需要相同我知道它不是下载,但下载总是一种使用链接的方式。也许你能够将这些代码组合起来并使其有效。

note that download links are always opened in a new window but automatically close.

请注意,下载链接始终在新窗口中打开,但会自动关闭。

I hope you will be able to make some progress

我希望你能取得一些进展

#1


0  

Your content-disposition must containattachment to allow the user to download it, it should be something like this:

您的内容处置必须包含允许用户下载的附件,它应该是这样的:

response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) + '.mp4'

#2


0  

I don't know a lot about python but I saw that you have only one reaction so I have done my bit of research and this is what I found. Click link open in other window need same I know it's not a download but a download is always a way of using a link.
Maybe you are able to combine those codes and make it work.

我不太了解python,但我看到你只有一个反应,所以我做了一些研究,这就是我发现的。点击其他窗口中打开的链接需要相同我知道它不是下载,但下载总是一种使用链接的方式。也许你能够将这些代码组合起来并使其有效。

note that download links are always opened in a new window but automatically close.

请注意,下载链接始终在新窗口中打开,但会自动关闭。

I hope you will be able to make some progress

我希望你能取得一些进展