Laravel Vapor环境下无法下载S3存储的DOCX、XLSX类型文件问题咨询
问题复现
- 托管环境:Laravel Vapor
- 异常表现:PNG、JPG、PDF类文件可正常从AWS S3下载,DOCX、XLSX类文件下载失败,推测是CloudFront请求头未放行对应文件类型导致
- 下载实现代码:
/** * Download file from storage * @param Document $document * @return StreamedResponse */ public function download(Document $document): StreamedResponse { return Storage::disk('s3')->download($document->path); }
- 已配置的请求头:
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
解决方案
你的请求头中包含*/*通配符,不是导致异常的原因,可按以下步骤排查修复:
- 手动指定下载响应头,避免Storage门面自动识别MIME类型出错,修改代码如下:
public function download(Document $document): StreamedResponse { $mimeType = Storage::disk('s3')->mimeType($document->path); // 替换为实际存储的文件名字段 $fileName = $document->name; return Storage::disk('s3')->download($document->path, $fileName, [ 'Content-Type' => $mimeType, 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", ]); }
- 在
vapor.yml中添加Office类型文件的配置规则,确保CloudFront放行对应类型:
cache: - '*.docx' - '*.xlsx' headers: '*.docx': Content-Type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' '*.xlsx': Content-Type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
- 检查S3文件元数据,确保上传时已指定正确的MIME类型,上传代码参考:
Storage::disk('s3')->put($filePath, $content, [ 'ContentType' => $uploadedFile->getMimeType() ]);
- 若以上配置不生效,进入Vapor控制台对应项目的CDN配置页,将
Content-Type加入允许传递的请求头、响应头列表,避免CloudFront拦截自定义头。
内容的提问来源于stack exchange,提问作者Tanner
相关产品推荐
相关产品推荐

