【问题标题】:A 'contents' key is required while uploading a file using Http client使用 Http 客户端上传文件时需要“内容”键
【发布时间】:2021-07-03 13:42:42
【问题描述】:

我正在努力解决一个奇怪的问题。我正在尝试使用 API 将文件上传到不同的服务器。我正在使用 Laravel 8.X 和使用 HTTP 客户端。下面是我从控制器调用的代码

if ($request->hasFile('uploadReceipt') && $request->file('uploadReceipt')->isValid()) { 
    $receiptContent = file_get_contents($request->file('uploadReceipt'));
    $originalName = $request->file('uploadReceipt')->getClientOriginalName();
    $responseUploadReceipt = Http::attach('attachment', $receiptContent, $originalName)
        ->withHeaders([
            'Accept'=> 'application/json', 
            'Authorization' => 'Bearer '.$userAccessToken 
        ])
        ->post($endpoint, $requestData); 

    dd($responseUploadReceipt->json()); 
} else { 
    dd ("Else"); 
} 

我在文件vendor/guzzlehttp/psr7/src/MultipartStream.php:86 中得到一个“内容”密钥是必需的 我花了将近 12 个小时,但无法解决这个问题。我也尝试过像

这样的流
$receiptContent = fopen($request->file('uploadReceipt'), 'r'); 

但同样的问题。我遵循文档中提到的相同方式。任何可以帮助我的人将不胜感激。

感谢和问候 阿什什

【问题讨论】:

    标签: laravel http file-upload multipartform-data


    【解决方案1】:

    我认为这行是问题所在:

    $receiptContent = file_get_contents($request->file('uploadReceipt'));
    

    文档中的示例不使用Request$request->file('uploadReceipt') 应该返回一个 Illuminate\Http\UploadedFile 的实例,我很确定 file_get_contents 不能使用 UploadedFile 作为参数。

    深入研究类文件,似乎有一种方法可以获取UploadedFile的内容:

    Illuminate\Http\UploadedFile

        /**
         * Get the contents of the uploaded file.
         *
         * @return false|string
         *
         * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
         */
        public function get()
        {
            if (! $this->isValid()) {
                throw new FileNotFoundException("File does not exist at path {$this->getPathname()}.");
            }
    
            return file_get_contents($this->getPathname());
        }
    

    改用$receiptContent = $request->file('uploadReceipt')->get();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 2018-10-12
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      相关资源
      最近更新 更多