PHP cURL:将文件从表单上传到远程API?
我正在尝试在我的网站上上传表单上的文件,然后将其传递到远程 API。
这是我的 PHP:
$fields = array(
'file'=>$_FILES["mediaupload"],
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
);
$fields_string = http_build_query($fields);
$url = my_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);
目前我不断收到文件无法正确处理的错误消息。 API 期望所有字段都是 POST 字符串,但文件除外,它期望以二进制形式。
我知道在无法访问远程 API 的情况下,对你们来说调试这个会很困难,但是我是否做了任何明显错误的事情,或者这应该有效?
非常感谢。
I'm trying to upload a file on a form on my site, and then pass it on to a remote API.
This is my PHP:
$fields = array(
'file'=>$_FILES["mediaupload"],
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
);
$fields_string = http_build_query($fields);
$url = my_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);
At the moment I keep getting error messages that the file could not be processed properly. The API expects all fields as POST strings except the file, which it expects in binary.
I know it's going to be tough to debug this for you guys without access to the remote API, but am I doing anything obviously wrong, or should this work?
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用curl 上传文件不会像这样工作。您需要首先使用 php 的 move_uploaded_file 将文件保存在本地,然后获取文件的路径。在字段中添加此内容,
另外,
我不确定字段数组是否需要转换为字符串才能用作后字段。根据手册,它可以直接是一个 array() 。
File upload using curl does not work like this. You need to first save the file locally using php's
move_uploaded_file
then get the path to file. In the fields add this,Also,
I'm not sure if fields array needs to be converted to string to be used as postfields. According to manual it can be an array() directly.