php – 使用CURLOPT_POSTFIELDS POST文件时文件为空
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 使用CURLOPT_POSTFIELDS POST文件时文件为空,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1723字,纯文字阅读大概需要3分钟。
内容图文
我正在尝试使用RESTful Web服务上传文件,如下所示:
$filename = "pathtofile/testfile.txt";
$handle = fopen($filename, "r");
$filecontents = fread($handle, filesize($filename));
fclose($handle);
$data = array('name' => 'testfile.txt', 'file' => $filecontents);
$client = curl_init($url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
curl_close($client);
但我保持gettig文件为空,作为对此请求的响应.
我也试过发送文件路径,如:
$data = array('name' => 'testfile.txt', 'file' => 'pathtofile/testfile.txt');
curl_setopt($client, CURLOPT_POSTFIELDS, $data);
或者:只发送文件的内容,如:
curl_setopt($client, CURLOPT_POSTFIELDS, $filecontents);
但是同样的反应:文件是空的.
请注意:文件存在且不为空,我只是尝试仅上传文件而没有其他字段.
我看到this post,但同样的问题,任何想法?
解决方法:
试试这个:
$data = array ('myfile' => '@'.$filename);
这将为接收端填充$_FILE [‘myfile’].
编辑:要实际将文件内容作为正文,您可以直接执行:
//Get the file data
$body = file_get_contents ($filename);
$len = strlen ($body);
//Open a direct connection to the server on port 80
$socket = fsockopen ('hostname.example.com', 80);
//Write the HTTP request headers
fwrite ($socket, "POST /path/to/url HTTP/1.1\r\n");
fwrite ($socket, "Host: hostname.example.com\r\n");
fwrite ($socket, "Connection: Close\r\n");
fwrite ($socket, "Content-Length: " . $len . "\r\n");
//Empty line marks end of headers, start of body
fwrite ($socket, "\r\n");
//Actually write the body
fwrite ($socket, $body);
//Get the result (half a kB at a time)
$result = '';
while (!feof ($socket)) $result .= fread ($socket, 512);
//Clean up nicely
fclose ($socket);
请注意,该代码未经测试,但它应该为您提供一般的想法.
内容总结
以上是互联网集市为您收集整理的php – 使用CURLOPT_POSTFIELDS POST文件时文件为空全部内容,希望文章能够帮你解决php – 使用CURLOPT_POSTFIELDS POST文件时文件为空所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。