PHP中用cURL直接提交内存中多部分数据(无需存盘)
跳过存盘直接提交GD生成的图片到API
你可以通过内存流或者直接传递文件数据数组的方式跳过存盘步骤,直接把GD生成的图片数据提交给API,不需要写入磁盘。以下是两种可行方案:
方案一:使用php://temp内存流 + CURLFile(推荐,兼容PHP 5.5+)
利用PHP的内存流php://temp存储图片数据,再通过CURLFile对象告诉cURL读取这个内存流的内容,模拟文件上传:
//Start with a png image $image that is 1024x1024 //Shrink the image using GD $temp = imagecreatetruecolor(512, 512); imagecopyresampled($temp, $image, 0, 0, 0, 0, 512, 512, 1024, 1024); //Output the GD image to a string named $image_data ob_start(); imagepng($temp); $image_data = ob_get_contents(); ob_end_clean(); // 用内存流替代磁盘文件 $stream = fopen('php://temp', 'r+'); fwrite($stream, $image_data); rewind($stream); // 将指针移到流的开头 // 创建CURLFile对象,指定文件名和MIME类型 $curl_file = new CURLFile($stream, 'image/png', 'uploaded_image.png'); //Use cURL to post the file to an API $url = 'https://anapi.com'; $fields = array( 'image' => $curl_file, ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 其他必要的curl配置(比如获取返回结果) curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); // 关闭流和cURL资源 fclose($stream); curl_close($ch);
方案二:直接传递文件数据数组(PHP 7.0+支持)
PHP 7.0及以上版本允许直接在CURLOPT_POSTFIELDS的数组中传递包含文件数据的数组,无需创建物理文件或内存流:
//Start with a png image $image that is 1024x1024 //Shrink the image using GD $temp = imagecreatetruecolor(512, 512); imagecopyresampled($temp, $image, 0, 0, 0, 0, 512, 512, 1024, 1024); //Output the GD image to a string named $image_data ob_start(); imagepng($temp); $image_data = ob_get_contents(); ob_end_clean(); //Use cURL to post the file to an API $url = 'https://anapi.com'; $fields = array( 'image' => array( 'name' => 'uploaded_image.png', 'type' => 'image/png', 'data' => $image_data ), ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 其他必要的curl配置 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
注意事项
- 确保你的PHP版本支持对应的方法:
CURLFile从PHP 5.5开始引入,直接传递数据数组的方式从PHP 7.0开始支持。 - MIME类型
image/png要和你生成的图片格式匹配,如果是JPG则改为image/jpeg。
内容的提问来源于stack exchange,提问作者user6631314
相关产品推荐
相关产品推荐

