我认为这里的主要问题是您使用了错误的内容类型。
对于文件上传,您应该使用“Content-Type: multipart/form-data”。
取自维基百科(在多部分子类型中)MIME
MIME 类型 multipart/form-data 用于表示通过表单提交的值。最初定义为 HTML 4.0 的一部分,它最常用于通过 HTTP 提交文件。它在 RFC 7578 中指定,取代 RFC 2388。
我写了这个sn-p,希望对你有帮助(对不起非OOP版本的代码,我没有安装PHP 8,我用的是PHP 7.4,但你可以“翻译”很容易:D):
<?php
//This is a dummy data array, will contain your form fields (Advice: never trust user input, always check the values given before submitting)
$data = [
'field1' => 'value',
'field2' => 'value2',
'field3' => 123
];
//The path to the file you want to upload
$fileName = 'somefile.xlsx';
$filePath = './../files/'.$fileName;
//Security check
if (file_exists($filePath))
{
//Adding the file to the $data array
$data['file'] = curl_file_create($filePath, mime_content_type($filePath), $fileName);
//Initialize the cURL handle
$ch = curl_init('https://some-random-site.com/api/some/random/endpoint');
//Set the request method (HTTP verb)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
//This will make curl "return" the response as string when we call curl_exec()
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//This SHALL NOT be used in production, unless you know the implications!!! But, if you have an HTTPS endpoint with a self-signed certificate you can skip checks
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//======
//We set the data we want to send (curl will "transform" this for us
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//Here the important part, setting the right content-type
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
//Execute the call and get the response as string
$res = curl_exec($ch);
if ($res === false)
{
//An error occurred, print out
echo 'ERROR: '.curl_error($ch);
}
else
{
//Execution succeeded, do whatever with the response
//Hint: this does not mean that the server answered with a success status but rather, it indicates that the curl execution has succeeded
//If you want to check the HTTP status of the request you can get it like this:
//$info = curl_getinfo($curl);
//echo $info['http_code'];
//Do whatever with the response (I'm just printing it).
echo $res;
}
curl_close($ch);
}
else
{
echo 'File not found.';
}
我真的希望这会有所帮助,不幸的是,我不知道您将请求提交到的 URL/API,因此我无法在您的端点上对其进行测试。我自己做了一个端点:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'PUT')
{
$c = file_get_contents('php://input');
die(var_dump($c));
}
我得到的输出显示了所有字段和文件上传。
--------------------------05a7619c906d94df Content-Disposition: form-data; name="field1" value
--------------------------05a7619c906d94df Content-Disposition: form-data; name="field2" value2
--------------------------05a7619c906d94df Content-Disposition: form-data; name="field3" 123
--------------------------05a7619c906d94df Content-Disposition: form-data; name="file"; filename="./../conf/test.xlsx" Content-Type:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
........LOTS_OF_BYTES_OF_THE_XLSX_FILE_:P......
--------------------------05a7619c906d94df--