首页 > 解决方案 > PHP:在 WordPress 中点击链接时通过 AJAX 下载文件

问题描述

我目前正在尝试使用 PHP AJAX 请求从我的服务器下载文件。我是这样构建的:

首先我得到所有文件(在这个例子中只有一个)并建立一个链接:

$invoice_number_base = 'RE-2018-12-00000039-E';

//Get all generated PDF file names by tmp path and invoice number base
foreach ( glob( '/var/www/vhosts/localhost/httpdocs/wp-content/uploads/wpo_wcpdf/attachments/' . $invoice_number_base . '*.pdf' ) as $file ) { ?>
    <a target="_blank" class="admin_et_pb_button"
       onclick="showGenInvoice('<?php echo $file ?>')">
        <?php echo basename( $file ) ?>
    </a>
<?php }

这会在此处生成此链接:

<a target="_blank" class="admin_et_pb_button" onclick="showGenInvoice('/var/www/vhosts/localhost/httpdocs/wp-content/uploads/wpo_wcpdf/attachments/RE-2018-12-00000039-E.pdf')">RE-2018-12-00000039-E.pdf</a>

现在我已经构建了我的 JS 函数以在用户单击按钮时调用 AJAX 函数:

function showGenInvoice(file) {

    var data = {
        'action': 'show_gen_invoice',
        'file': file
    };

    jQuery.post(ajaxurl, data, function () {
    }).fail(function () {
        alert('An error occured!')
    });
}

(该函数有参数链接,其中包含我服务器上每个文件的路径)

在此之后,我在 WordPress 中构建了 AJAX 回调:

/**
 * Get generated invoice from attachments folder so the invoices which are sent by email
 */
add_action( 'wp_ajax_show_gen_invoice', array( $this, 'show_gen_invoice' ) );
public function show_gen_invoice() {
    //Get file path from request
    $file = $_POST['file'];
    if ( is_admin() && file_exists( $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 ) );
        ob_clean();
        flush();
        readfile( $file );
        wp_die();
    } else {
        wp_send_json_error( null, 500 );
        wp_die();
    }
}

但遗憾的是,当我按下按钮时,没有下载任何文件。没有错误,只是没有任何反应。这里有什么问题?

注意:

文件所在的文件夹是受保护的,不能用正常的页面url和/uploads/...

更新

请查看我的解决方案!当您想使用 PHP 从后端从服务器下载某些内容时,它是可用的。

标签: phpajaxwordpress

解决方案


感谢 ahamd 的提示。这是我对这个问题的解决方案:

新链接:

//Get invoices tmp path
$tmp_path = WPO_WCPDF()->main->get_tmp_path( 'attachments' );
//Get invoice number
$invoice_number_base = $invoice->get_number()->get_formatted(); ?>
<div class="wpo_wcpdf-generated-invoices-container">
    <?php
    //Get all generated PDF file names by tmp path and invoice number base
    foreach ( glob( $tmp_path . $invoice_number_base . '*.pdf' ) as $invoice ) { ?>
        <a target="_blank"
           class="admin_et_pb_button"
           href="post.php?invoice=<?php echo basename( $invoice ) ?>">
            <?php echo basename( $invoice ) ?>
        </a>
    <?php } ?>
</div>
<?php

在浏览器中显示文件的代码:

/**
 * Add file download functionality to admin post
 */
add_action( 'admin_init', 'show_gen_invoice' );
function show_gen_invoice() {

    //Check if invoice is set and get value = the path of the invoice
    if ( isset( $_REQUEST['invoice'] ) ) {

        //Get invoices tmp path
        $tmp_path = WPO_WCPDF()->main->get_tmp_path( 'attachments' );

        //Get invoice basename
        $invoice = urldecode( $_REQUEST['invoice'] );

        if ( is_admin() && file_exists( $tmp_path . $invoice ) ) {
            $content = file_get_contents( $tmp_path . $invoice );
            header( 'Content-Type: application/pdf' );
            header( 'Content-Length: ' . filesize( $tmp_path . $invoice ) );
            header( 'Content-Disposition: inline; filename=' . $invoice );
            header( 'Cache-Control: private, max-age=0, must-revalidate' );
            header( 'Pragma: public' );
            ini_set( 'zlib.output_compression', '0' );
            flush();
            die( $content );
        }
    }
}

我现在在浏览器中显示了该文件,但如果您想直接下载它,您可以使用我上面的工作代码来下载它。

我现在正在使用admin_init钩子将我的代码放入post.php可以$_REQUEST用来获取此文件的文件中。


推荐阅读