php - 使用 Curl 和 PHP 将文件发送到 Anonfile
问题描述
我正在尝试在anonfile上使用 curl 和 PHP 发送文件,但我得到了这个 json:
{"status":false,"error":{"message":"没有选择文件。","type":"ERROR_FILE_NOT_PROVIDED","code":10}}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://anonfile.com/api/upload");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'test.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
print_r($server_output);
curl_close ($ch);
换句话说,如何将这个命令翻译成 PHP?
curl -F "file=@test.txt" https://anonfile.com/api/upload
我尝试了几个例子,但仍然没有线索
$target_url = 'https://anonfile.com/api/upload';
$args['file'] = '@/test.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
解决方案
curl_setopt($ch, CURLOPT_POSTFIELDS,'test.txt');
不起作用,因为它实际上只是发送文字字符串test.txt
$args['file'] = '@/test.txt';
因为@
上传文件的前缀在 PHP 5.5 中已被弃用,在 PHP 5.6 中默认禁用,在 PHP 7.0 中被完全删除,所以无法正常工作。在 PHP 5.5 及更高版本中,使用CURLFile以multipart/form-data
格式上传文件。
从 PHP 5.5+ 开始(在这一点上很古老),
curl -F "file=@test.txt" https://anonfile.com/api/upload
翻译成
$ch=curl_init();
curl_setopt_array($ch,array(
CURLOPT_URL=>'https://anonfile.com/api/upload',
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>array(
'file'=>new CURLFile("test.txt")
)
));
curl_exec($ch);
curl_close($ch);
推荐阅读
- java - Java 11 获取当前的微秒?
- r - 使用 Leafpop 将图像添加到地图
- python - 如何摆脱异常处理
- javascript - React Native - 使图像大小适应布局
- android - 在 React Native Expo 中运行后台工作程序以执行密集任务
- r - 使用 browser() 语句调试 R Shiny 不会那么痛苦
- ruby-on-rails - 在 iFrame 中加载的 Rails 应用程序会话不起作用
- php - Heroku:PHP 位置和名称
- ruby-on-rails - 如何用ruby中的数组中的元素替换字符串中的单词?
- javascript - Mongoose 使用填充()检查 LeanDocument 类型