首页 > 解决方案 > 带有 HTTP::attach 错误的 Laravel 发布文件:需要“内容”键

问题描述

我尝试按照文档中的描述通过 Http 门面发送文件我不明白失败的原因,我添加了内容 $stage->pdfFile,我通过 file_get_contents() 获取它并且它不是空的,它是文件的数据。

我总是收到错误:需要“内容”键。

public function sendPdfFile($id)
    {

        try {

            $stage = Stage::findOrFail($id);
            $stage->setPdfFileAttribute();

            //test
            //dd($stage->pdfFile);//ok

            $response = Http::attach('pdfFile',$stage->pdfFile,$stage->n_stage.'.pdf')
                ->post($this->endpointFileUploadUrl);


        }catch(\Exception $exception){
            $this->error("error sending file ".$stage->n_stage.".pdf to ".$this->endpointFileUploadUrl.' : '.$exception->getMessage());
        }

    } 

这是关于https://laravel.com/docs/8.x/http-client的文档

$response = Http::attach(
    'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('http://example.com/attachments');

我就这样改了,同样的错误:

public function sendPdfFile($id)
    {

        try {

            $stage = Stage::findOrFail($id);
            $stage->setPdfFileAttribute();

            //test
            //dd($stage->pdfFile);//ok

            $response = Http::attach('pdfFile',$stage->pdfFile,$stage->n_stage.'.pdf')
                ->post($this->endpointFileUploadUrl, [
'name' => 'pdfFile',
'contents' => $stage->pdfFile,
]);


        }catch(\Exception $exception){
            $this->error("error sending file ".$stage->n_stage.".pdf to ".$this->endpointFileUploadUrl.' : '.$exception->getMessage());
        }

    } 

标签: phplaravellaravel-8

解决方案


仅对于多部分请求,您应该将数组中的每个参数及其内容作为方法的第二个参数(数组的数组)传递post

$response = Http::attach('pdfFile',$stage->pdfFile,$stage->n_stage.'.pdf')
->post($this->endpointFileUploadUrl, [
                [
                    'name' => 'param 1',
                    'contents' => 'param 1 contents'
                ],
                ....
    ]);

推荐阅读