Welcome to OStack Knowledge Sharing 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 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...