我需要将文件(base64 字符串格式)上传到 REST API,该 API 将接受 blob 作为文件内容。在 javascript 中,我需要做的是将 base64 字符串转换为 blob 数据,并将其传递给 FormData 并将其发布到 API 端点。
我只是不知道如何使用 PHP、使用 GuzzleHttp 客户端来做到这一点。
我希望有 PHP 技能的人可以告诉我如何在 PHP 中做到这一点。我在谷歌上搜索,但到目前为止似乎没有找到适合我的解决方案。
非常感谢。
只是一个粗略而简单的想法...我添加了尽可能多的评论以使其易于理解...希望这对您有用!
$base64String = 'your_base64_encoded_data_here'; // base64 string
//decode the base64 string and write it to a temporary file:
$decodedData = base64_decode($base64String);
$tempFilePath = tempnam(sys_get_temp_dir(), 'upload');
//replace sys_get_temp_dir() with your custom dir if you want to change
file_put_contents($tempFilePath, $decodedData);
//or use fwrite
//fwrite(fopen($tempFilePath,"w+"),$decodedData);
使用 Guzzle 创建请求并上传文件:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\MultipartStream;
$apiUrl = 'https://your_api.com/upload'; // replace with your api endpoint
$client = new Client();
// prepare data for multipart/form-data
$multipart = new MultipartStream([
[
'name' => 'file', // form field name
'contents' => fopen($tempFilePath, 'r'),
'filename' => 'uploaded_file' // file name
]
]);
// create a psr-7 request object
$request = new Request('POST', $apiUrl, ['Content-Type' => 'multipart/form-data; boundary=' . $multipart->getBoundary()], $multipart);
// send request
$response = $client->send($request);
// final response
echo $response->getBody();
// delete the temporary file
unlink($tempFilePath);
//Or move to a a folder and schedule a cronjob to clean up the folder