Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用CURLOPT_POSTFIELDS发布文件时,文件为空_Php_File_Rest_Post_Curl - Fatal编程技术网

Php 使用CURLOPT_POSTFIELDS发布文件时,文件为空

Php 使用CURLOPT_POSTFIELDS发布文件时,文件为空,php,file,rest,post,curl,Php,File,Rest,Post,Curl,我正在尝试使用RESTful web服务上载文件,如下所示: $filename = "pathtofile/testfile.txt"; $handle = fopen($filename, "r"); $filecontents = fread($handle, filesize($filename)); fclose($handle); $data = array('name' => 'testfile.txt', 'file' => $filecontents); $cl

我正在尝试使用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);
但是相同的响应:文件是空的

请注意:文件存在且不是空的,我只是尝试只上载文件,而不上载其他字段

我看到了,但同样的问题,有什么想法吗?

试试这个:

$data = array ('myfile' => '@'.$filename);
这将为接收端填充
$\u文件['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);

请注意,该代码未经测试,但它应该能为您提供总体思路。

感谢您的回复,但我尝试过,但问题似乎出在服务本身,我查看了他们的文档,他们说整个请求正文保存为一个新文件,那么
$data
看起来会是什么样子?在这种情况下,我应该向服务传递什么参数?应该是文件的内容和内容类型,还是什么?当我只发送文件内容时,没有任何内容发布到服务。哇,这是一个奇怪的API。你能发一个链接到它吗?如果它确实是这样工作的,那么您可能必须跳过cURL,自己通过直接套接字写入来完成,因为cURL for PHP似乎不允许您直接设置帖子正文(只接受数组或URL编码的字符串)。请注意,他们说:文件应以二进制流的形式发送,但正如我在上面的问题中所说的那样,我尝试了该方法,但该方法有效,但文件url给了我:错误的请求或错误的参数,并且我检查了服务器,没有上载或上载文件为空,你能解释一下吗。我已经修改了我的答案,以展示如何使用直接套接字写入来完成。非常感谢你的回答,我尝试了它。它没有错误,也没有响应。我使用Firebug进行调试,但没有上传文件,我怎样才能得到他们在文档中以
file\u key
file\u url