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

Laravel中如何在Bootstrap模态框内预览AWS S3存储的PDF文件

解决Bootstrap模态框内预览AWS S3存储PDF的问题

一、修改Laravel控制器代码

原控制器直接输出文件内容的方式不适合AJAX处理,改为生成带自定义响应头的S3预签名URL,强制浏览器以预览模式打开而非下载:

public function BackgroundVerifyShow(Request $request)
{
    $s3 = \Storage::disk('s3');
    $filePath = $request->path;

    // 校验文件是否存在
    if (!$s3->exists($filePath)) {
        return response()->json([
            'status' => false,
            'message' => '文件不存在'
        ]);
    }

    // 生成带预览响应头的预签名URL
    $command = $s3->getDriver()->getAdapter()->getClient()->getCommand('GetObject', [
        'Bucket' => config('filesystems.disks.s3.bucket'),
        'Key' => $filePath,
        'ResponseContentDisposition' => 'inline; filename="' . basename($filePath) . '"',
        'ResponseContentType' => 'application/pdf'
    ]);

    $presignedUrl = \Aws\CommandPool::createPresignedRequest($command, '+10 minutes');

    return response()->json([
        'status' => true,
        'url' => (string)$presignedUrl
    ]);
}

二、添加Bootstrap模态框HTML结构

在视图页面合适位置(如底部)插入模态框结构:

<!-- PDF预览模态框 -->
<div class="modal fade" id="pdfPreviewModal" tabindex="-1" aria-labelledby="pdfPreviewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="pdfPreviewModalLabel">PDF预览</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <iframe id="pdfPreviewFrame" src="" width="100%" height="700px" style="border:none;"></iframe>
      </div>
    </div>
  </div>
</div>

三、更新前端AJAX逻辑

修改PDFOPEN函数,在请求成功后加载预签名URL并显示模态框:

function PDFOPEN(path) {
    $.ajax({
        type: 'post',
        url: '{{ route('background.pdf.show') }}',
        data: {
            "_token": "{{ csrf_token() }}",
            'path': path
        },
        success: function(data) {
            if (data.status == true) {
                // 给iframe赋值预览URL
                $('#pdfPreviewFrame').attr('src', data.url);
                // 打开模态框
                $('#pdfPreviewModal').modal('show');
            } else {
                toastr.error(data.message);
            }
        },
        error: function() {
            toastr.error('请求失败,请稍后重试');
        }
    });
}

关键注意事项

  • 若使用Bootstrap 4.x,模态框调用逻辑与5.x一致,但HTML结构需对应调整(如data-dismiss替代data-bs-dismiss)。
  • 预签名URL有效期可根据需求调整(示例为10分钟)。
  • 确保S3存储桶CORS配置允许你的域名访问,否则iframe无法加载资源:
    <CORSConfiguration>
      <CORSRule>
        <AllowedOrigin>https://你的域名.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
      </CORSRule>
    </CORSConfiguration>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:35:13