创建下载链接

时间:2017-05-22 04:03:16

标签: php

file.php

<a href="download.php?filename=<?php echo $basename; ?>">&nbsp;&nbsp;<?php echo $filename; ?></a>

$basename将返回一个值,例如 id_filename.extension ,这是服务器内文件的真实名称

的download.php

<?php
    require_once 'database.php';
    require_once 'session.php';
    require_once 'session-login.php';
    require_once 'session-timeout.php';
    require_once 'valid-user.php';

    $folder = $userid;
    $file_name = $_GET['filename'];
    $file = 'C:xampp/htdocs/project/user/'.$folder.'/'.$file_name;

    if (file_exists($file)) {
        header('Content-Type: ' . mime_content_type($file_name));
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
    } else {
        header('HTTP/1.1 404 Not Found');
    }
?>

它确实下载了文件。但是当我打开文件时,即使服务器中存在文件,我也会收到错误:

<b>Warning</b>:  mime_content_type(id_filename.extension): failed to open stream: No such file or directory in <b>C:\xampp\htdocs\project\download.php</b> on line <b>12</b><br />

2 个答案:

答案 0 :(得分:1)

您应该从$file(完整路径)获取mime类型,而不仅仅是$filename

$file = 'C:xampp/htdocs/project/user/'.$folder.'/'.$file_name;
if (file_exists($file)) {
    header('Content-Type: ' . mime_content_type($file));

答案 1 :(得分:1)

我认为你应该输入:

Content-Type: application/octet-stream

而不是

Content-Type: mime_content_type($file_name)