Mp4 下载导致浏览器播放文件而不是下载 [英] Mp4 Download causes browser to play file instead of download

查看:30
本文介绍了Mp4 下载导致浏览器播放文件而不是下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上,我向用户播放 mp4 内容.我也允许用户下载.但是,在 Chrome 中,它似乎会在内部播放器中自动播放文件,而不是下载文件.

In my website I stream users mp4 content. I also allow users to download. However in Chrome it seems to automatically play the file in an internal player instead of downloading the file.

如何强制浏览器下载文件.

How do I force the browser to download the file instead.

问候和感谢克雷格

推荐答案

您必须使用 HTTP 标头Content-Disposition"和Content-Type: application/force-download"' 这将强制浏览器下载内容而不是在那里显示.

You have to use the HTTP header "Content-Disposition" and 'Content-Type: application/force-download' which will force browser to download the content instead of displaying it there.

根据您使用的服务器端语言,实现会有所不同.在

Depending upon the server side language you are having the implementation differs. In case of

PHP:

    header('Content-Disposition: attachment; filename="'.$nameOfFile.'"');

将为您完成这项工作.

当然,为了简化和概括所有文件,您可能需要编写一个方法来将链接路由到可下载内容.

Ofcourse to simplify and generalize this for all your files, you may need to write a method which will route a link to downloadable content.

您可以在 html 中显示的链接如下:

The link you can show in the html will be like:

<a href="http://yoursite.com/downloadFile?id=1234">Click here to Download Hello.mp4</a>

在服务器端,您需要一个在/downloadFile 上调用的脚本(取决于您的路由),通过 id 获取文件并将其作为附件发送给用户.

And in the server side, you need a script which is being called on /downloadFile (depending on your routing), get the file by id and send it to user as an attachment.

<?php

 $fileId = $_POST['id'];

 // so for url http://yoursite.com/downloadFile?id=1234 will download file
 // /pathToVideoFolder/1234.mp4
 $filePath = "/pathToVideoFolder/".$fileId."mp4";
 $fileName = $fileId."mp4"; //or a name from database like getFilenameForID($id)
 //Assume that $filename and $filePath are correclty set.
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Type: application/force-download');
readfile($filePath);

这里的内容类型:应用程序/强制下载"将强制浏览器显示下载选项,无论 mime 类型的默认设置是什么.

Here 'Content-Type: application/force-download' will force the browser to show the download option no matter what's the default setting is for a mime-type.

无论您的服务器端技术是什么,要注意的标头是:

No matter what your server side technology is, the headers to look out for are:

'Content-Description: File Transfer'
'Content-Type: application/force-download'
'Content-Disposition: attachment; filename="myfile.mp4"

这篇关于Mp4 下载导致浏览器播放文件而不是下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆