You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX请求下载接口无法触发ZIP文件下载的问题求助

AJAX请求下载接口无法触发ZIP文件下载的问题求助

大家好,我现在碰到一个棘手的问题:我的代码能成功在storage/app/public目录下生成ZIP文件(已经执行过php artisan storage:link创建软链接了),但通过AJAX请求下载接口的时候,文件就是不自动触发下载,有没有大佬能帮忙看看哪里出问题了?

以下是我的PHP后端代码:

public function download()
{
    $zip_file = 'screenshots.zip';
    $zip_path = storage_path('app/public/'.$zip_file);
    $zip = new \ZipArchive();
    $zip->open($zip_path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

    $path = storage_path('app/public/screenshots');
    $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));

    foreach ($files as $name => $file) {
        if ($file->isDir()) {
            continue;
        }
        $filePath = $file->getRealPath();
        $relativePath = 'screenshots/' . substr($filePath, strlen($path) + 1);
        $zip->addFile($filePath, $relativePath);
    }

    $zip->close();

    return response()->download($zip_path);
}

对应的前端AJAX代码:

function downloadImages() {
    const token = document.querySelector('meta[name="csrf-token"]').content;
    fetch('/download', {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json, text-plain, */*',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': token
        },
        method: 'get',
    })
    .then((response) => {
        console.log('download');
    })
    .catch((error) => {
        console.log(error);
    })
}

我已经确认ZIP文件确实生成了,文件大小也正常,直接在浏览器访问/download路由是能正常触发下载的,只有通过AJAX请求的时候没反应,控制台只打印了download,没有任何报错信息。实在搞不懂哪里出问题了,求指点!

备注:内容来源于stack exchange,提问作者marcelo2605

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 13:04:10