Laravel Zip Archive无法在浏览器中下载

时间:2017-02-17 15:43:51

标签: php laravel download http-headers ziparchive

我正在尝试将一堆PDF压缩在一起并在浏览器中下载,此时PDF文件被压缩并下载到PDF文件存储的文件夹中,而不是通过用户浏览器下载到他们的下载文件夹中,I有一个类似(和更简单)的功能,下载单个PDF,所以感觉我错过了一些相当明显的东西..

$ id是一个逗号分隔的文件名列表,然后将其拆分为一个数组,用于循环并添加到zip文件。这个位有效,认为它可能是标题问题或响应。

任何帮助都非常感激。

public function downloadMultiple($id) {

    $id_array = explode(',', $id);

    $public_dir = storage_path();
    $zipFileName = time().'.zip';

    $zip = new ZipArchive;

    if ($zip->open($public_dir . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {

        foreach($id_array as $file) {

            $file_path = storage_path($file).".pdf";

            if (file_exists($file_path)) {
                $zip->addFile($file_path,$file.".pdf");
            }
        }

        if ($zip->close()) {
            $filetopath = $public_dir.'/'.$zipFileName;

            $headers = [
                'Cache-control: maxage=1',
                'Pragma: no-cache',
                'Expires: 0',
                'Content-Type : application/octet-stream',
                'Content-Transfer-Encoding: binary',
                'Content-Type: application/force-download',
                'Content-Disposition: attachment; filename='.time().'.zip',
                "Content-length: " . filesize($filetopath)
            ];

            if (file_exists($filetopath)) {
                $response = response()->download($filetopath, $zipFileName, $headers);
                //$response->deleteFileAfterSend(true);
            } else {
                return ['status'=>'zip file does not exist'];
            }

        } else {
            return ['status'=>'zip file could not close'];
        }

    } else {
        return ['status'=>'Could not create new zip'];
    }
}

更新: 绝对得到返回并创建文件,它似乎似乎没有为用户下载,下面是检查员带回来的东西,所以显然没有按预期工作

enter image description here

在提到发送到控制器的代码时,

值得一试

let xhr = new XMLHttpRequest(),  self = this;
             xhr.open('GET', window.location.origin+'/download-multiple/' + this.selected);
             xhr.onload = function () {
             };
             xhr.send();

1 个答案:

答案 0 :(得分:1)

假设您已经进入控制器方法的那一部分,我相信问题是您没有回复您的回复:

if (file_exists($filetopath)) {
    // $response = response()->download($filetopath, $zipFileName, $headers);
    // $response->deleteFileAfterSend(true);
    return response()->download($filetopath, $zipFileName, $headers)->deleteFileAfterSend(true);
} else {
    return ['status'=>'zip file does not exist'];
}

编辑:问题是您是否正在尝试通过AJAX加载文件,而您无法按照您尝试的方式执行此操作(see here for examples on how to do it)。将您的JavaScript更改为:

let xhr = new XMLHttpRequest(),  self = this;
window.location = window.location.origin+'/download-multiple/' + this.selected