2014-10-04 107 views
2

我的根目录中有一个名为files的文件夹。 此文件夹包含范围从1 Kb-1 GB的文件。将文件从服务器下载到客户端的计算机

我想要一个php脚本,可以简单地使用AJAX异步下载文件。

此代码启动下载脚本点击一个文件时:

JQUERY

$('.download').click(function(){ 
    var src =$(this).attr('src'); 
    $.post('download.php',{ 
     src : src //contains name of file 
    },function(data){ 
     alert('Downloaded!'); 
    }); 
}); 

PHP

<?php 
    $path = 'files/'.$_POST['src']; 
    //here the download script must go! 
?> 

这将是最好,最快,安全下载文件的方式?

+0

- 为什么?你需要做什么不能通过让服务器管理它来完成?为什么你需要涉及Ajax? – Quentin 2014-10-06 06:12:28

回答

3
<?php 
/** 
* download.php 
*/ 

if (!empty($_GET['file'])) { 
    // Security, down allow to pass ANY PATH in your server 
    $fileName = basename($_GET['file']); 
} else { 
    return; 
} 

$filePath = '???/files/' . $fileName; 
if (!file_exists($filePath)) { 
    return; 
} 

header("Content-disposition: attachment; filename=" . $fileName); 
header("Content-type: application/pdf"); 
readfile($filePath); 

而实际上AJAX请求使用Content-disposition: attachment时是不必要的,“我想一个PHP脚本,可以异步使用AJAX只需下载一个文件”

<a href="download.php?file=file1.pdf">File1</a> 
+1

如果我不知道“内容类型”,该怎么办? – 2014-10-04 13:27:42

+1

只是不使用它时。它有助于浏览器确定文件打开程序(电影,图像,MS字等) – 2014-10-04 13:41:00

+0

您不能使用Content-Type。除非您重写,否则PHP将默认声明它是一个HTML文档。 – Quentin 2014-10-06 06:12:58

相关问题