首页 > 解决方案 > PHP使用目录字符串上传文件

问题描述

我有一个字符串表示这样的文件路径:D:/folder/another_folder/image_name.png.

我想使用 PHP curl 将其作为文件发送我已经这样做了,但它不起作用

$ch = curl_init();   
if (function_exists('curl_file_create')) { // php 5.5+  
    $cFile = curl_file_create('D:/folder/another_folder/image_name.png');  
}else{  
    $cFile = '@' . realpath('D:/folder/another_folder/image_name.png');  
} 

$fields['userPhoto'] = $cFile;  
$fields['uploadedfrom'] = 'web';  

curl_setopt($ch, CURLOPT_URL, 'http://some_url.com');  
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);   
curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
    'Content-Type: application/json'  
));  
$result = curl_exec($ch);  

curl_close($ch);  

问题是我从 csv 文件中获取文件路径而不是浏览它
任何人都可以帮助解决这个问题并告诉我如何通过 PHP CURL 从字符串发送文件?

标签: phpcurl

解决方案


您的问题是您使用的是 json_encode。json_encode 无法编码 CURLFile 对象。此外,JSON 不是二进制安全的,因此您不能使用 json 发送 PNG 文件(PNG 文件包含二进制数据,例如包括 FF/255 字节,这在 json 中是非法的。也就是说,一种常见的解决方法是对二进制进行编码base64 中的数据,并以 json 格式发送 base64)。停止使用 json,只需给 CURLOPT_POSTFIELD 数组,curl 会将其编码为multipart/form-data-format,这是通过 http 协议上传文件的事实标准。走那条路,你还必须摆脱Content-Type: application/json标题,curl会自动Content-Type: multipart/form-data为你插入。


推荐阅读