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

Laravel使用HTTP::attach上传文件报错:需包含'contents'键

解决Laravel HTTP::attach上传文件报错"A 'contents' key is required"问题

问题原因

代码中直接将fopen返回的文件资源传给attach方法,Laravel HTTP客户端无法正确解析该资源的内容;另外当$file参数为null时,会传入无效文件资源,触发该错误。

修复方案

方案1:直接使用文件路径(推荐)

Laravel的attach方法支持直接传入文件路径,内部会自动处理文件读取,避免手动操作资源的问题:

static public function apiRequestWithFile($method, $endpoint, array $params = [], $file = null)
{
    $apiKey = env('API_KEY');
    $baseUrl = env('BASE_URL');

    $http = Http::withHeaders([
        'Authorization' => $apiKey,
    ]);

    // 仅当文件存在时添加上传操作
    if ($file && file_exists($file)) {
        // 方式1:传入文件内容
        $http->attach('file', file_get_contents($file), 'file.csv');
        // 方式2:更简洁的直接传文件路径
        // $http->attach('file', $file, 'file.csv');
    }

    $response = $http->$method($baseUrl . $endpoint, $params);

    return $response->json();
}

方案2:正确处理文件资源

如果必须使用fopen,需确保资源有效并在使用后关闭:

static public function apiRequestWithFile($method, $endpoint, array $params = [], $file = null)
{
    $apiKey = env('API_KEY');
    $baseUrl = env('BASE_URL');

    $http = Http::withHeaders([
        'Authorization' => $apiKey,
    ]);

    if ($file && file_exists($file)) {
        $fileResource = fopen($file, 'r');
        if ($fileResource) {
            $http->attach('file', $fileResource, 'file.csv');
            fclose($fileResource); // 使用后关闭资源
        }
    }

    $response = $http->$method($baseUrl . $endpoint, $params);

    return $response->json();
}

关键注意事项

  • 必须添加$file参数的空值和文件存在性判断,避免传入无效路径或null引发错误。
  • 调用attach后请求会自动转为multipart/form-data格式,$params会以表单参数形式发送,无需额外处理格式。

内容的提问来源于stack exchange,提问作者Md. Mostafijur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:52:09