我将使用 php 转换一些文件并将其作为 HTTP POST 请求的一部分发送。我的代码中有一部分:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: " . $this->contentType."",
'content' => "file=".$file
)
));
$data = file_get_contents($this->url, false, $context);
变量$file
必须是我要发送的文件的字节表示吗?
这是在不使用表单的情况下以 php 发送文件的正确方法吗?你有什么线索吗?
还有使用PHP将文件转换为字节表示的方法是什么?
您可能会
发现使用CURL要容易得多,例如:
function curlPost($url,$file) {
$ch = curl_init();
if (!is_resource($ch)) return false;
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , 0 );
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 0 );
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt( $ch , CURLOPT_POST , 1 );
curl_setopt( $ch , CURLOPT_POSTFIELDS , '@' . $file );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_VERBOSE , 0 );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$url 是您要发布到的位置,$file是您要发送的文件的路径。
奇怪的是
,我刚刚写了一篇文章并说明了相同的场景。(phpmaster.com/5-inspiring-and-useful-php-snippets)。但为了帮助您入门,以下是应该可以工作的代码:
<?php
$context = stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=--foo'r'n",
"content" => "--foo'r'n"
. "Content-Disposition: form-data; name='"myFile'"; filename='"image.jpg'"'r'n"
. "Content-Type: image/jpeg'r'n'r'n"
. file_get_contents("image.jpg") . "'r'n"
. "--foo--"
)
));
$html = file_get_contents("http://example.com/upload.php", false, $context);
在这种情况下,制作一个模拟的Web表单并在启用Firebug或其他功能的情况下通过Firefox运行它,然后检查发送的请求会有所帮助。从那里你可以推断出要包括的重要内容。