如何完成批处理并重定向输出

3
我正在处理一个Drupal 7项目。我正在使用批处理,在其中实现一些操作,并显示进度条。在我的“formulaire_finished”函数中,作为批处理的最后一个操作执行,我想下载一个文件,然后重定向到另一个页面,因为进程已经结束。
然而,readfile()函数使用了drupal_exit(),所以我的重定向没有完成。
以下是我的代码:
function formulaire_finished($success, $results, $operations) {
    if ($success) {
        $path = $results['infos']['path'];
        download_file($path);
        // Redirection
        drupal_goto($_SESSION['my_page'], array('query' => array('details' => '1')));
    } else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE), )));
    }
}

下载功能:

function download_file($path) {
    $dir = $path;
    $filename = basename($dir);
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        drupal_add_http_header('Pragma', 'public');
        drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    } else {
        drupal_add_http_header('Pragma', 'no-cache');
    }
    drupal_add_http_header('Expires', '0');
    drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
    drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($dir) . ';');
    drupal_add_http_header('Content-Transfer-Encoding', 'binary');
    drupal_add_http_header('Content-Length', filesize($dir));
    readfile($dir);
    unlink($dir);
    drupal_exit();
}

欢迎提出各种想法。

2个回答

2
在下面的函数中,你能否尝试让该函数始终返回true。
function download_file($path) {
    $dir = $path;
    $filename = basename($dir);
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        drupal_add_http_header('Pragma', 'public');
        drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    } else {
        drupal_add_http_header('Pragma', 'no-cache');
    }
    drupal_add_http_header('Expires', '0');
    drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
    drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($dir) . ';');
    drupal_add_http_header('Content-Transfer-Encoding', 'binary');
    drupal_add_http_header('Content-Length', filesize($dir));
    readfile($dir);
    unlink($dir);

    //drupal_exit();
    // Can you use simple return here
    return true;

}

谢谢你的回答。我已经尝试过了,但问题是如果没有这个exit()函数,readfile()函数就不会被执行。所以,我通过返回true来重定向,但我的文件没有被下载... - Underground72

1
我认为在批处理操作完成回调期间不应输出文件以供下载。您应该将文件保存到Drupal的文件系统中并保存对该文件的引用。然后可以在批处理完成后下载它。

我认为完全否定批处理完成后下载文件的需求是不准确的。我目前正在处理一个批处理并将其保存到Drupal的文件系统中,然后当批处理完成时,应该下载文件并将用户重定向回来。我认为这是Drupal无法很好处理的一个有效用例。 - kalpaitch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接