我尝试通过 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());
}
}
仅对于多部分请求,您应该将数组中的每个参数及其内容作为
post
方法的第二个参数(数组的数组)传递。
$response = Http::attach('pdfFile',$stage->pdfFile,$stage->n_stage.'.pdf')
->post($this->endpointFileUploadUrl, [
[
'name' => 'param 1',
'contents' => 'param 1 contents'
],
....
]);
如果有人仍然面临这个问题,请找到适合我的代码。
来自 Laravel 应用程序的请求 1
request = Http::withHeaders(['Accept' => 'Application/Json']);
foreach ($this->files as $key => $file) {
$request->attach("file{$key}", fopen($file['file']->getRealPath(), 'r'), $file['filename']);
}
$response = $request->post(
"{$this->url}",
[
'firstname' => $this->firstname,
'lastname' => $this->lastname,
'phone' => $this->phone,
'reference' => $this->reference,
'file_count' => count($this->files)
]
);
Laravel 应用程序 2 中处理传入请求的代码
$file_count = $request->file_count;
for($i=0; $i<$file_count; $i++){
Document::create([
'name' => $request->file("file{$i}")->getClientOriginalName(),
'path' => $request->file("file{$i}")->store('documents', 'public'),
]);
}
希望它能帮助别人..
$data = [
'name' => $request->get('full_name'),
'email' =>$request->get('email')
];
我将上面的数组格式更改为下面给出的数组格式,它开始为我工作。
$data = [
[
'name' => 'full_name',
'contents' => $request->get('full_name')
],
[
'name' => 'email',
'contents' => $request->get('email')
]
];