Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

google chrome - Mp4 Download causes browser to play file instead of download

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.

Regards and thanks Craig

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.'"');

will do the job for you.

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.

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>

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);

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...