php - 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 从字符串发送文件?
解决方案
您的问题是您使用的是 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
为你插入。
推荐阅读
- javascript - 在 onclick 中使用变量(即使以后更改,也要保留旧变量值)
- c++ - 尝试通过 c++ 程序中的 system() 函数使用 cl Visual Studio 命令进行命令行构建时出现 vcvars32.bat 问题
- python - spaCy 命名实体识别无法识别食品等产品实体
- python - 如何使用 Tensorflow 功能 API 沿批量维度进行广播?
- javascript - Javascript / Typescript:比较日期、字符串和时刻变量
- kubernetes - AWS EKS Kubernetes 错误:无法识别策略:版本“v1beta1”中的种类“策略”没有匹配项
- c# - 计算字母评估量表的差异
- c - 我应该在 /proc 中读取文件时处理 EINTR
- javascript - 仅当首先执行上面编写的指令时,如何运行 res.render()?
- c# - 只包含一件事的 if 语句是什么意思?