使用JavaScript AJAX调用PHP后端打开PDF

Mas*_*hit 6 javascript php pdf ajax jquery

我有一个方法,通过AJAX调用后端,从MySQL数据库获取一个blob文件,由PHP检索.

问题是PHP变量包含一个字符串,但AJAX调用是空的,PDF函数不起作用.

这是AJAX代码,它被调用.

self.showPDF = function() {
    $.ajax({
            type: 'GET',
            url: BASEURL + 'index.php/myprofile/openUserPDF/' + auth,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        })
        .done(function(data) {
            console.log(data);
            window.open("data:application/pdf," + escape(data));
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            alert("Could not open pdf" + errorThrown);
        })
        .always(function(data) {});
}
Run Code Online (Sandbox Code Playgroud)

这是后端的PHP函数,我使用的是CodeIgniter框架.

public function openUserPDF($token) {
    if ($this->input->is_ajax_request()) {
        $userid = $this->myajax->getUserByAuth($token);
        if ($userid) {
            /* If we have an impersonated user in the session, let's use him/her. */
            if (isset($_SESSION['userImpersonated'])) {
                if ($_SESSION['userImpersonated'] > 0) {
                    $userid = $_SESSION['userImpersonated'];
                }
            }
            /* now we get the pdf of the user */
            $this->load->model('user_profile');
            $images = $this->user_profile->getUserImageForPDF($userid);
            $pdfString = $images[0]->image;
            $this->output->set_content_type('application/json');
            return $this->output->set_output(json_encode($pdfString));
        } else {
            return $this->output->set_status_header('401', 'Could not identify the user!');
        }
    } else {
        return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
    }
}
Run Code Online (Sandbox Code Playgroud)

我确实将blob检索为字符串,但基本上就是它,它不会返回到AJAX调用.

Pla*_*ato 1

当您可以简单地使用或直接输出PDF 时,将 PDF 中潜在的巨大内容加载到内存中是一个非常非常非常非常糟糕的主意。file_get_contentsreadfile

JavaScript

self.showPDF = function() {
    window.open(BASE_URL + '/index.php/myprofile/openUserPDF/' + auth);
}
Run Code Online (Sandbox Code Playgroud)

PHP函数

//... validation and querying ...

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

readfile($pdfString);
Run Code Online (Sandbox Code Playgroud)

(来自How to render pdf file by using php 的标题;有关使用 PHP 渲染 PDF 文件的更多信息,请参阅 参考资料)