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

如何将API接口文件保存到Laravel应用的public目录?

如何将API返回的文件保存到Laravel的public文件夹

你可以通过以下步骤将Guzzle请求返回的文件内容保存到Laravel的public目录:

方法一:使用Laravel Storage门面(推荐)

Laravel的文件系统门面提供了便捷的文件操作方法,public磁盘对应storage/app/public目录,执行php artisan storage:link后,前端可通过/storage/xxx直接访问该目录下的文件。

修改后的代码:

use Illuminate\Support\Facades\Storage;

$client = new \GuzzleHttp\Client();

// 替换{id}为实际的签名请求ID
$response = $client->request('GET', 'https://api-sandbox.yousign.app/v3/signature_requests/{id}/documents/download', [
    'headers' => [
        'accept' => 'application/pdf',
        'authorization' => 'Bearer 00...........',
    ],
]);

// 读取响应流中的文件内容
$fileContent = $response->getBody()->getContents();

// 定义保存路径(相对于storage/app/public)
$savePath = 'documents/signed_document.pdf';

// 保存文件到public磁盘
Storage::disk('public')->put($savePath, $fileContent);

方法二:直接写入public目录

如果不需要通过Storage门面,也可以直接用原生PHP方法写入public目录:

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api-sandbox.yousign.app/v3/signature_requests/{id}/documents/download', [
    'headers' => [
        'accept' => 'application/pdf',
        'authorization' => 'Bearer 00...........',
    ],
]);

$fileContent = $response->getBody()->getContents();

// 直接写入public目录根目录
file_put_contents(public_path('signed_document.pdf'), $fileContent);

进阶:自动获取API返回的文件名

如果API响应头包含Content-Disposition,可以解析它获取原始文件名,避免硬编码:

use Illuminate\Support\Facades\Storage;

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api-sandbox.yousign.app/v3/signature_requests/{id}/documents/download', [
    'headers' => [
        'accept' => 'application/pdf',
        'authorization' => 'Bearer 00...........',
    ],
]);

$fileContent = $response->getBody()->getContents();

// 解析Content-Disposition头获取文件名
$dispositionHeader = $response->getHeaderLine('Content-Disposition');
preg_match('/filename="?([^"]+)"?/', $dispositionHeader, $matches);
$fileName = $matches[1] ?? 'default_filename.pdf';

// 保存文件
Storage::disk('public')->put('documents/' . $fileName, $fileContent);

注意事项

  • 确保目标目录(如storage/app/public/documents或public)有写入权限,Laravel应用进程需要能写入这些目录。
  • 务必替换请求URL中的{id}为实际的签名请求ID,否则API请求会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:52:41