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

Laravel 8+DataTables:如何将jQuery变量传入{{ Storage::url() }}

Laravel 8 DataTables 生成正确文件下载链接

方法一:前端列渲染直接处理

在你的Blade视图的DataTables配置中,针对file列使用render函数拼接路径并生成a标签:

$(document).ready(function() {
    $('#your-table-id').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('your.data.route') }}",
        columns: [
            // 其他列配置
            {
                data: 'file',
                name: 'file',
                render: function(data) {
                    // 拼接完整访问路径
                    const fullHref = '/storage/' + data;
                    // 返回构造好的a标签,如需显示真实文件名,可替换Test.pdf为data.split('/').pop()
                    return `<a href="${fullHref}" target="_blank">Test.pdf</a>`;
                }
            }
        ]
    });
});

方法二:后端Controller提前构造字段

在Controller的DataTables逻辑中,直接生成带HTML的链接字段,避免前端拼接:

use DataTables;

public function dataTableSource(Request $request)
{
    $query = YourModel::query();

    return DataTables::of($query)
        ->addColumn('file_link', function($row) {
            $fullPath = '/storage/' . $row->file;
            // 构造a标签字符串
            return "<a href='{$fullPath}' target='_blank'>Test.pdf</a>";
        })
        ->rawColumns(['file_link']) // 告知DataTables该字段为HTML,无需转义
        ->make(true);
}

之后在Blade的DataTables配置中,直接使用新增的file_link列即可:

columns: [
    // 其他列
    { data: 'file_link', name: 'file_link' }
]

注意事项

确保已执行php artisan storage:link创建storage目录的软链接,这样/storage/开头的路径才能正确映射到storage/app/public下的文件。

内容的提问来源于stack exchange,提问作者Alexis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:05:20