简体   繁体   中英

Link/button to download file from subfolder— browser just browses

I have tried:

var url = '/files/123.txt';
$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = url;
});

This just makes firefox browse to the text file, and not prompt a download.

I have also tried this function:

var downloadURL = function downloadURL(url)
{
    var iframe;
    iframe = document.getElementById("hiddenDownloader");
    if (iframe === null)
    {
        iframe = document.createElement('iframe');  
        iframe.id = "hiddenDownloader";
        iframe.style.visibility = 'hidden';
        document.body.appendChild(iframe);
    }
    iframe.src = url;   
}

Which has the same problem -- opens in browser, no download prompt.

I have tried using apache:

<Files *.txt>
  ForceType applicaton/octet-stream
</Files>

I placed a .htaccess with this code in both the subfolder and parent folder. This apache method only seems to work if the requested text file is in the same folder as the web page. When the text file is placed into subfolder /files/ , then the same problem persists -- no download prompt.

Really now, is there a secret way to do this?

Utilize PHP headers for most versatility. How to do this can be found here: http://webdesign.about.com/od/php/ht/force_download.htm

If you want to use the .htaccess way it's the headers you need to change rather than the content type:

<FilesMatch "\.(?i:txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM