AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf
Force Files to Download (Not Open in Browser)
Chris Coyier
on
make sure to put this poop in .htaccess
This was a brilliant typo.
Success! I’ve popped the code above into my .htaccess file and all works perfectly. However, once the file has downloaded my page load stalls and doesn’t return to the original page the file was downloaded from?
Thanks for this, man! So cool, so simple!
By the way, your website is for me one of the most reliable regarding many many things, of course, in particular CSS. You (all) give such a great helping hand!! Thanks a million for that.
It is not working for MS Edge.. Any solution?
Wow, I’ve been trying to figure out how to do this for a very, very (very) long time! Is there any way you can make it specific, for example, if I click “link 1”, I can view the file in browser, but if I click “link 2”, the “AddType” function is applied, and I am forced to download?
Thanks in advance, and sweet snippet!
It’s not an ideal solution to your problem, but you could have a php wrapper for download links that simply takes an argument that is the filename and then reads the file (assuming local files) and before outputting the file to the user you send headers with the filetype. see http://www.php.net/manual/en/function.header.php for more information about php and headers.
Hi Michal Kopanski,
Did you ever get this figured out? I also want to put 2 links on my webpages. One to view the pdf in the browser and one to force the download.
@Andy, I’m probably a bit late, but you can use the HTML5 “download” attribute on the link you want to have download. It’s not as fool-proof as this .htaccess method, but it is easy.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
I would think you can do that: Begin without force-download code in the .htaccess file in your web root or its parents in the filesystem, or in your Apache server’s configuration. Enable .htaccess files in the configuration.
Place two folders in the web root, one called, “in-browser” and one called “download.” In both, place an index file containing links to files on your site.
In the download folder, place this article’s code in the .htaccess file.
Whenever you want to display your in-browser link, just point it to /in-browser/ and likewise your downloads link can be directed to /download/.
Your download ,htaccess only affects the /download/ folder and any subfolders under /download/.
This is a great one. I had forgotten about it before but I’m glad I found it again!
Thanks
What abouton a windows server? I can’t get the .htaccess for to work – is this only for apache users?
Correct. Anything .htaccess is only Apache.
Your solution is to delete IIS and install Apace ;)
Yes, .htaccess is an Apache server function. Windows will not accept the filename .htaccess. It is claimed to be an extension with no file name. Use quotes around the name in Notepad to save .htaccess or use third-party software. It will work in a Windows install of Apache. and best to place the server and your website on the same hard drive — this avoids need for drive letters. It will work exactly as it does in Linux on your web host.
Hi!, that was awesome, i just found this tutor on google,
thanks!, and now its possible to not use header function.
I m using apache2triad and in this there is no .htaccess named file so now what todo?
now stop trying to be a webmaster until you know what you’re doing
Now then Ilort, that’s not very helpful. One doesn’t just become a webmaster overnight, it’s a learning process. How would you feel if your teacher said “don’t try to learn until you have learnt”?
Gilank, if your site doesn’t have an .htaccess file just make one in a text editing programme.
Now then, that wasn’t too hard was it.
.htaccess is a file with no “name” in front of the “extension,” as seen in Microsoft products and Windows OS. It is actually a hidden file in Linux, so designated by the leading dot.
That said, create a text file in Notepad, and fill it with the material presented at the top of this page. Name it with quotes: “.htaccess”
It will save properly in the Windows OS if the name with its leading dot is in quotes in the Notepad Save dialog. Upload this file to the web root of your site next to your index.html (.php, .cgi, etc.) page which opens when someone dials up your website without specifying beyond the “example.com.”
Your host may not allow the use of .htaccess, and has the server configured not to look for it, even if it is an Apache server in Linux.
I run Apache on Windows for my local testing, and Apache does use .htaccess as if it were on Linux. Save your perl.exe on the same drive with the server, as \usr\bin\perl.exe, and your Perl scripts will work as if they were looking at the Perl interpreter at /usr/bin/perl.
I prefer to answer people’s beginner questions with something other than “get out of it until you know what you’re doing.” That was rude of the other person who so replied.
Sorry for the unhelpful “stop trying to be a webmaster.” Create .htaccess in Windows Notepad by quoting the name in the save-as dialog. Better yet, there are a host of third-party Notepad replacements.
I like it short ;)
AddType application/octet-stream .doc .mov .avi .pdf .xls .mp4
Where I have to include this code? To the css, js or php? Thanks!
Alex: Add it to the .htaccess file on your Apache server.
Thank you so much, the above solution didn’t work for me.
thanks a lot!!!
Wow, beautiful trick! Was trying to figure this thing out forever, thank you!
Awesome!
Thank youy so much for that trick.
great post /…… :)
Hi,
Some people use:
ForceType application/octet-stream
Header set Content-Disposition attachment
Do you know wich’s better?
Thanks!
I have used AddType application/octet-stream .png and it forces the download, the only issue is that it opens a new empty tab that it closes after it finishes the donwload, but if I hit the cancel button then the new empty tab stays open. Is there anyway to get the pop up window in the same tab that I click the link
don’t use target=”_blank” on you link?
thank u very much i have been trying abouth 2 hours :)
does this work for you in all browsers? i’ve got it only working in chrome but not ie and firefox
ah it’s like that per default in chrome, so i’m not sure what i made wrong, nothing but that in the .htaccess?
Just perfect :-)
Hi!
I test this trick, and work perfect in Chrome 15, Firefox 7, but in IE 9 this broken… show many invalid characters.
Searching more info found this code:
Please replace ** by as appropriate, for some reason in the comments do not see these characters.
Test again and voila work in Chrome, Firefox and IE. In FF and IE show “save as…” dialog box, but in chrome download directly. How to fix this last issue? Force to Chrome show “save as…” dialog box…
Greetings from Peru
Pavel
@Pavel
I did as your posted, Opera & Firefox did good but my IE still open the PDF as page not donwload it. Any advice ?
This worked perfectly for me. Thank You!
This worked for me too. The AddType wasn’t working in Chrome on Mac (didn’t test anything other than chrome and safari).
Thanks!
Works! For Me, For Our Mp3 Files..Thank You Very Much!
Solution from Pavel Valencia works. (I tried many other advices)
thanks a lot for this tip!
Thanks, this tip works great on Opera & Firefox but not on my IE. I use Win XP SP2 and my IE version is 5.2.
I also tried Pavel Valencia’s tip but it still doesn’t work for my IE.
Any advices will really appreciated.
Note: I’m using WordPress.
Thank you!!
Pavel Valencia’s solution works great. Thanks!
(notice that you need to change the ** with < and > like HTML tags
< should be <
Does anyone know how to make this work for mobile? I’ve tried both Chris’ solution and Pavel’s, however mp3s still stream rather than download on mobile devices. Any ideas?
can you give a example for this how I can link a pdf file to download.
where add the above code
To the .htaccess file on your Apache server
FTP to your site and create a file named .htaccess in your files directory. In that file put the following lines:
Header set Content-Disposition attachment
This particular example will force files with doc, mov, pdf, rtf, or txt to download instead of being shown in the browser.
Cheers
ughh.. looks like this comment area doesn’t render the code.
Just take a look at: http://wiki.dreamhost.com/Htaccess_tricks
Scroll down to the Force File Download section.
it didn’t work for Chrome 17 for Mac…
I came back to post the solution that worked, but it’s almost the same as Pavel Valencia published above
I’m not sure how to mix both, because this one does prevent lower/uppercase issues
Thanks!! Works Nice
Thank you very much!
For me this worked also in Firefox! As the simple AddType application/octet-stream .pdf line did not.
Thanks very much!
Thanks ! This was just what I was looking for and very helpful. Gotta love .htaccess files.
If you’re getting Internal Server error after posting the HTACCESS codes in .HTACCESS document… is there anything amiss? BTW, the website is a WordPress system.
For internal Server error : you must enable header module ->
cd /etc/apache2/mods-available
a2enmod headers
service apache2 restart
Pavel Valencia’s version works like a charm! Thanks
I have created .htaccess file , and applied code as ” AddType application/octet-stream .txt ” , but still the file is opening in browser , it don’t allows to downloading the file.
Hi, I don´t know why but this doesn´t work with Google Chrome. I don´t have a problem with any other browser. Is it only with me? or anybody else has the same problem?
Have you cleared your cache in Chrome? If you have been testing the same file by the same name, you ‘ll need to do that before it will work.
Ok, I’ve been searching ALL DAY for an answer to this, I’m not sure i’m in the right thread but I’m going for it anyway! I’m running on a Windows 7 computer. I just purchased a digital scrapbook paperpack. She says she sent me the 12 individual files in a zipped folder. However, when I downloaded it it appeared in my downloads folder as a blank piece of paper. It appears to be a octet-stream file and none of my programs will open it. I have no idea what to do with it. She then sent me the individual files, unzipped as JPEGS. When I downloaded them the only thing I could open them in is Windows Media Gallery. When I tried to rightclick>copy>paste into a specific folder it appeared again as just a blank piece of paper and am still unable to open it in anything. (Photoshop is where I’m trying to use it) ANY suggestions would be GREATLY appreciated!
Response.AddHeader(“Content-Disposition”, “Attachment;filename=somefile.ext”);
This will help you
this is so very great…. thanks a lot!
Hi – I know this thread has been going for a while and I hate to kick a dead horse, but we are running into trouble with iOS devices.
Has anyone found a solution that works for Mobile Safari? The htaccess adjustment works great for desktop browsers, but iOS devices still stream MP3s.
Any suggestions?
You’d better take this question to StackOverflow and report back with the answers :)
Where would it download to? iOS doesn’t have an accessible file system.
Hey Craig,
Did you find an answer to this? I wish to prevent streaming on iOS devices. I understand there’s no filesystem, so it obviously won’t download, but I’d at least like to prevent streaming! And I would like to allow downloads on mobile devices that can download, like Android phones.
To prevent streaming on devices that cannot download, perhaps sniff for device user-agent strings and serve alternate content to devices that want to stream.
Great trick!
But I have still a problem with video files (.mov, .mp4)
it seems it starts download the file and immediately opens quicktime.
but with large size files quicktime can’t open properly.
Is there a way to force the whole download?
thanks
Chris,
That’s the problem. It doesn’t download. But nekkid MP3 links play on an iOS device. And with several thousand people accessing the several 50MB files for each product our server is under severe strain – maxing our bandwidth @ 1&1. We considered off-loading the files, but the bandwidth costs at Amazon would be more than our revenue…
We need a way to prevent iOS devices from automatically playing nekkid MP3 links. Currently we wrapped ’em in a ZIP file but that creates a new set of ‘how do I unzip files?’ problems.
Any suggestions?
Will server environment variables store iOS user-agent strings? Sniff for the offending user-agent and serve alternate content in place of the streaming files.
Thanks. worked for me. I hope future HTML version allow such an option.
I couldn’t get Chromium/Chrome to respond to AddType application/octet-stream .pdf so instead I used htaccess to send the Content-Disposition: attachment header as Chromium Issue 142947 seemed to indicate was preferred. However, this still didn’t work. It seems Chrome interprets Content-Disposition rather strictly, as detailed here by Foo Compels You. Having uppercase characters in my filename caused Chrome to open the file in the in-browser PDF viewer but changing these to lowercase caused the file to download, as intended. Interesting how letter case affects things. Hope this helps.
I would not use this approach as it currently prevents Chrome users from downloading the file.
A link to a PDF it will not do anything when a Chrome user clicks on it.
Chrome 24 – BAD – link does not work at all – user cannot access the file
Firefox 17 – GOOD – works as expected
IE 9 – OK – It downloads the file then opens it with the PDF viewer
I would use the FilesMatch approach one of the other commenters noted – it doesn’t prevent any of your users from getting the file.
<FilesMatch “.(?i:pdf)$”>
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
thx for this tip..
I’ve asked our resident programmer to force our PDF to download, and I received this response, of which, being a graphic designer, not a programmer, I understand pretty much nothing. Is he correct and am I asking for something particularly complex?:
“I know what it takes to force a browser to download rather than
display. In fact I have some pages that do just that. It’s a
server-side issue, because you have to specifically populate the
response header with an “application-octet” stream directive, along with
filename. If you know a special way of doing it client-side, via HTML,
CSS, and/or javascript that all browsers understand in the same way, by
all means let me know and I can put it up. Otherwise it takes hours to
get the server to do it just right. Hours that I won’t have for at
least a few weeks.”
<a href="link" download>download this file</a>
But for the moment is only working in chrome
I have been using a series of google drive accounts for download for a 300 meg .exe
as I had no idea on how popular it would be.
I wanted users to stay on the page, so all I did was add “target=”_top”> to the URL.
My download link is a graphic, but the latter does me fine.
Perfect! simply done the job … thx
Thanks for this tip. I wouldn’t even have thought of using htaccess for this. Glad you were so willing to share!
Hey all,
I made a .htaccess file in the top-most folder (world wide web/sitename/.htaccess) of my site and added the AddType and FilesMatch codes but neither of them seem to work.
I am using Joomla! 3.0 for my companies intranet page and we have a TON of PDF’s that need to be force downloaded. There is no extension that can do this that I know of.
Any other ideas or am I doing something wrong?
Could always try PHP (if you havn`t found a solution yet, hopefully you have)
http://snipplr.com/view/22546/php-force-file-download-instead-opening-in-new-tabwindow/
I had to stick the .htaccess file in the actual folder in which the files to be downloaded are stored. Using WordPress. I used:
AddType application/octet-stream doc odf pdf rtf txt png jpg
Seems to work with Chrome, Safari, Opera, FireFox, but not IE.
Hope this helps!
Hey guys can someone leave a code?! i really dont understand how to do that :(
Now you can also do this with HTML5.
Source (Click)
Wow! Awesome Marko! I didn’t know that it was possible through the HTML5. Very cool! Thank you for sharing it.
Hi
I have a client who wants to do the opposite. Some browsers open, some download.
Can you override this and force the browser to open in a new window!?
Or is that a really silly question?
Steve
This has been a really helpful thread, and Rudolf’s version works great. What I like is that Firefox, IE, and Safari give the user the option to open or download. Only Chrome forces the user to download, which I am afraid is going to confuse some of my less tech-savvy end users. Is there a way to “force” the “open or download” option in Chrome?
Oh man! First result in Google and this is it. Thanks a lot for this post. Solved all of my problem. However still testing if the result is the same with All main browsers ans well as mobile browsers :)
Do not work in Chrome version 30.0.1599.69.
Tried solutions from comments as well – any hints?
Best way to do that is this:
Download PDF
–a href=”http://website.com/filename.pdf” download— Download PDF –/a—
Replace –to < open tag
Replace —to > close tag
You’re welcome ;)
I need to download .sql file in a folder. I have a button named download. And button has it’s own value. ie.
(sql filename action)
(1.sql ——- download,
2.sql ——– download)
when clicking on download button
if(isset($_REQUEST[‘download’])){echo $_REQUEST[‘download’]; //result either 1.sql or 2.sql}
1.sql,2.sql are in the same folder in which my download.php file is placed.
This work is for my word press site.My need is to download 1.sql or 2.sql to my computer when corresponding button is clicked.
ie
if(isset($_REQUEST[‘download’])){download file.(ie.download $_REQUEST[‘download’]).
This is for a new plug in .
i write code if(isset($_REQUEST[‘download’]))
{
$pathtoyourfile=plugins_url(‘yu-DB-Backup/’);
$filename=$_REQUEST[‘download’].’.sql’;
header(“Content-Type: application/octet-stream”);
header(“Content-Disposition: attachment; filename=\””.$filename.”\””);
readfile($pathtoyourfile.$filename);
}
then
Warning: Cannot modify header information – headers already sent by (output started at H:\xampp\htdocs\yu\wp-admin\menu-header.php:179) in H:\xampp\htdocs\yu\wp-content\plugins\yu-DB-Backup\inc\inc.wpgc_db_backup.php on line 6
Warning: Cannot modify header information – headers already sent by (output started at H:\xampp\htdocs\yu\wp-admin\menu-header.php:179) in H:\xampp\htdocs\yu\wp-content\plugins\yu-DB-Backup\inc\inc.wpgc_db_backup.php on line 7
Warning: readfile(http://localhost/yu/wp-content/plugins/yu-DB-Backup/2.sql) [function.readfile]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in H:\xampp\htdocs\gcertificate\wp-content\plugins\WPGC-DB-Backup\inc\inc.wpgc_db_backup.php on line 8 .
Please help me if anyone know the answer
Is there anyway to have this only for one specific pdf vs all pdfs on the server?
Hello,
Which directory should I place the .htaccess file with this line in it: “AddType application/octet-stream .csv”
Where my csv file is or where my php scripts are?
Using WordPress.
Thanks,
Moe
Put your .htaccess in the directory containing the CSV file. Here the .htaccess is only in effect in this directory and any subdirectories, and not on “sibling” or “parent” branches of your directory tree.
You may place the .htaccess file in the parent of this directory, and it will work equally well here, but will also affect all subdirectories under the parent.
I do not know about WordPress, as most of my site development work has been in HTML or PHP, but this would be my first inclination of placement.
If you want to force all files in a directory to download, create a .htaccess file in that directory, then paste this in it:
Don’t stick this in your root level .htaccess file. It will cause all the files on your server to download.
Hope helps you!
$mime_types=array(
“pdf” => “application/pdf”,
“txt” => “text/plain”,
“html” => “text/html”,
“htm” => “text/html”,
“exe” => “application/octet-stream”,
“zip” => “application/zip”,
“doc” => “application/msword”,
“xls” => “application/vnd.ms-excel”,
“ppt” => “application/vnd.ms-powerpoint”,
“gif” => “image/gif”,
“png” => “image/png”,
“jpeg”=> “image/jpg”,
“jpg” => “image/jpg”,
“php” => “text/plain”,
“csv” => “text/csv”,
“xlsx” => “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,
“pptx” => “application/vnd.openxmlformats-officedocument.presentationml.presentation”,
“docx” => “application/vnd.openxmlformats-officedocument.wordprocessingml.document”
);
“
Source: http://w3webtools.com/simple-page-download-file-using-php-and-jquery/
You can also use a addon for firefox or a service like http://savedirectlink.com to download, but not open some direct file link.
Firefox, Chrome, Opera, Android Browser and Chrome for Android support the
download
attribute on links, mentioned by a couple of other commentators:See the caniuse.com entry for
download
.Thank You!
Caleb G – thanks – that worked for me.
Can someone please tell me how to set up my FTP so that files are opened in the browser and NOT downloaded?
I seem to have the opposite problem everyone else has. I want my files to be displayed in the browser and not downloaded. Everything I’ve tired to make that happen has failed.
Someone suggested setting up a .mtaccess file in my /var/www/html directory, but the only examples they gave are to force downloads.
Thank you.
Bob, did you ever get anything to work. I have exactly the same problem and thought this was a past i had made until I saw your name
A nasty solution, this makes the server pass the incorrect mime type to the browser, tricking it into treating the data as an unknown format. Better educate your users and explain a browser can save any file,.
Nice solution, I’ve added some proper filename matching,
anti-mimetype sniffing and HTML5 solutions too (may combined)
reference:
http://icompile.eladkarako.com/properly-set-content-disposition/
http://stackoverflow.com/a/34758866/257319
I am using this to force download .log files. Issue is when the logs files get rotated. Example: .log0001, .log0002 or .log12345
Any wildcard that I could use to download file extensions starting .log?
You can use a Perl server-side script. It has been awhile since I’ve been involved with Perl, but it will tackle this job. PHP may also have the capability to do the same. You may also be able to use JavaScript on the client side as well.
I would like to point out, that all suggested solutions are not working if the user tries to download the file with a 1.0 – 4.3 Android operation system and the Chrome or stock Android browser.
See this almost 5 years old bug report:
https://code.google.com/p/android/issues/detail?id=19951
Either you are ignoring this problem (should be fixed with KitKat), or you are informing your users to force download with long pressing the download button, or point out that there are other browsers for Android available, which none of them struggling with this task.
But don’t waste your time trying to fix this problem. There is no fix – both Chrome mobile and the stock Android browser are using the build-in Android download manager to download files – and as a web developer you are unable to get this very download manager to do it’s job right.
Please, I need assistance I had tried several method but all is to no avail.
here is my code;
This is pretty much the top result for when you search for this, so I feel I should mention that if you’re using Java Servlets, you can call response’s setType method
This is very nice if you’re say, generating a .csv file like I was.
So if you’re using Servlets in some fashion and need to do this, this is a way of doing it.
can tell anyone me.
How can i download php file using .htaccess coding
That’s incorrect. Omit the dot before file extensions then it would work
When i put someone link on my post, its redirecting visitors to his home page, how to fix pls
any similar solutions for web.config??
Hi. I am trying download a file from a URL when a button is pressed, and I like your method, but I am hosting on Github Pages, there is no .htaccess. Is there any way I can do it using pure JavaScript and/or HTML? I have tried the
<a>
attribute but that only works if the file is hosted by you. Can someone please help me?Hello! please I will like to know if there is a way I can force download of files I uploaded on googledrive. I have tried but it opens the mp3 file in the browser instead and then provides options where they are many including download but I will want to know if there is a way to force this download directly when using href. If I paste the link direct to browser it downloads but when I add hyperlink like href it opens in browser instead.
Any way to make this work normal on wordpress?
Any one mind if I throw a twist into this age old topic?
I have done a serious amount of searching, but I am having a hard time thinking outside the box on this one. I am looking for a brighter mind than mine.
I want to force the download of EVERYTHING. Not just a few file extensions. There is some simple code that works in .htaccess for this…
This works awesome. So awesome that when you load/refresh/reload the page (directory index in my case), it immediately pops open a download prompt with
download.html
. I can not even get a directory listing as it now wants to download the page.So that is not the answer. What I would like to find, is perhaps an expression that I could use that would allow everything
^
, except for html or php files!(\.(html|php)$
.In addition, whats the format look like when the file doesn’t have an extension at all?
I am looking to those nerdier than me. ;)