通过ajax调用文件php下载文件

时间:2017-06-09 14:43:38

标签: javascript php arrays json

我有一个PHP文件和其他JavaScript。在JavaScript中,我将变量与文件存在的位置传递,但在PHP端没有识别并且没有正确下载文件。

JavaScript代码:

var nameFile = oEvent.getParameters().listItem.getTitle();
var directory = "C:/xampp/htdocsui5launchpad/WebContent/documents/";

window.location =directory;

$.ajax({
            url: 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php',
            type: 'POST',
            datatype: "json",
            data: { album: nameFile },
            success: function (response, data, xhr) {
                window.location = 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php';

            },
            error: function (response) {
                console.log("Error in PHP, downloadPDF.php ");
            }
        });

PHP代码:

    if(isset($_POST["album"])){
        $name = $_POST["album"];
    }

    $dir = "C:/xampp/htdocs/ui5launchpad/WebContent/documents/";

    $file = $dir . $name;

    if( isset($file)) {
        //echo $file;

        if (file_exists($file)) {
            //echo $file;
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        }

    }

请帮帮我吗?

由于

1 个答案:

答案 0 :(得分:0)

您无需使用ajax下载文件。只需将文件直接链接到浏览器即可。

在link标签中输入如下属性:

<a href="http://example.com/file.pdf" download>Download</a>