下载文件而不是打开新窗口

时间:2015-01-23 10:29:19

标签: php html download

用户可以上传我的表单上的文档和详细信息,这些文档和详细信息将保存到数据库中,并创建一个文件夹来保存文档。他们可以上传.jpg .png .docx等。所以不仅仅是图片。

我现在想要显示这些文档的链接,当您点击链接时,它提供了在您的计算机上保存/打开文件的选项。相反,当我点击链接时,它会转到一个新页面并在那里显示图像。但因为他们可以上传pdf等word文档。你不能在新窗口中看到这些文件。

现在使用的方法不支持IE,这是必不可少的。

代码:

  if(isset($_POST["submit"])){

        $ref = $_POST["reference"];
        $query  = "SELECT * ";
        $query .= "FROM customers ";
        $query .= "WHERE reference = {$ref}";
        $results = mysqli_query($connection, $query);

        // Array to hold all results:
        $all = array();
        while ($customer_details = mysqli_fetch_assoc($results)) {
            // Append a new sub-array of the 3 other cols to
            // the main array's key by reference using the []
            // array append syntax
            $all[$customer_details['reference']][] = array(
                'doc1' => $customer_details['doc1'],
                'doc2' => $customer_details['doc2'],
                'doc3' => $customer_details['doc3']
            );
        }

        foreach ($all as $reference => $rows) {
          // Write out the reference, which was the array key
            echo $reference . "<br/>";
            // Then in a loop, write out the others
            foreach ($all as $reference => $rows) {
          // Write out the reference, which was the array key
            echo $reference . "<br/>";
            // Then in a loop, write out the others
            foreach ($rows as $row) {
                echo  "<a href='docs/1111111/1/" . $row['doc1'] . "' download='" . $row['doc1'] . "' >file1</a><br/>";
                echo  "<a href='docs/1111111/1/" . $row['doc2'] . "' download='" . $row['doc2'] . "' >file2</a><br/>";
                echo  "<a href='docs/1111111/1/" . $row['doc3'] . "' download='" . $row['doc3'] . "' >file3</a><br/>";
            }

        }
    }

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

您只需要在服务器上的.htaccess文件中添加代码行。 您可以根据扩展名更改文件类型(例如doc)

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

这里有3个选项,其中第3个选项: http://www.tipsandtricks-hq.com/forum/topic/force-a-file-to-download-instead-of-showing-up-in-the-browser