开发者

How to download a file on clicking the name of file using PHP?

I Have a list of information in which there is a field where name of file is hyperlinked. I want the user to download that particular file when he clicks on it.

so, How to download a file on clicking the name of file using PHP?

I tried it using ajax whose code is as below, but I do not get any file downloaded.

download.php

$filename = $_GET['val'];
         // Fetch the file info.
 $filePath = $_SERVER['DOCUMENT_ROOT'] . "/dfms/images/docs/".$filename;

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }

javascript function

<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function download(path,val) {
var req = Inint_AJAX();
req.open("GET", path+"download.php?val="+val); //make connection
//req.setRequestHeader("Content-Type", "applic开发者_运维百科ation/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
req.onreadystatechange = function () {
 if (req.readyState==4) {
      if (req.status==200) {

      }
 }
};

}
</script>

link to download

<a href="javascript:download('http://localhost/project/images/','DMS.doc');">DMS.doc</a>


so, How to download a file on clicking the name of file using PHP?

The easiest way should be linking to it.

<a href="download.php?......" target="_blank">DMS.doc</a>


You don't need AJAX for that, you cannot even do what you want using AJAX. If you want to obfuscate URL to a file, then replace your download function with this:

function download(path,val) {
    window.location.href = path+"download.php?val="+val;
};


     // Fetch the file info.


$filePath = $_SERVER['DOCUMENT_ROOT'] . "/dfms/images/docs/".$filename;



if(file_exists($filePath)) {
    $fileName = basename($filePath);
    $fileSize = filesize($filePath);

    // Output headers.
    header("Cache-Control: private");
    header("Content-Type: application/stream");
    header("Content-Length: ".$fileSize);
    header("Content-Disposition: attachment; filename=".$fileName);

    // Output file.
    readfile ($filePath);                   
    exit();
}
else {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜