是否可以在Kohana 3.2中模拟文件上传请求?我正在尝试以下但没有太多运气:
$file = file_get_contents('../../testimage.jpg');
$request = new Request('files');
$request->method(HTTP_Request::POST);
$request->post('myfile', $file);
//$request->body($file);
$request->headers(array(
'content-type' => 'multipart/mixed;',
'content-length' => strlen($file)
));
$request->execute();
答案 0 :(得分:0)
This Kohana forum post表示它应该是可能的。鉴于与您的代码的相似性,我猜你已经找到了。因为这不适合你,你可以试试cURL:
$postData = array('myfile' => '@../../testimage.jpg');
$uri = 'files';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
$response = curl_exec($ch);
如果您想使用Kohana请求,您可以尝试使用此代码构建您自己的多部分主体(我没有正确的设置来立即测试它,但它应该接近您需要的):< / p>
$boundary = '---------------------' . substr(md5(rand(0,32000)), 0, 10);
$contentType = 'multipart/form-data; boundary=' . $boundary;
$eol = "\r\n";
$contents = file_get_contents('../../testimage.jpg');
$bodyData = '--' . $boundary . $eol;
$bodyData .= 'Content-Type: image/jpeg' . $eol;
$bodyData .= 'Content-Disposition: form-data; name="myfile"; filename="testimage.jpg"' . $eol;
$bodyData .= 'Content-Transfer-Encoding: binary' . $eol;
$bodyData .= $contents . $eol;
$bodyData .= '--' . $boundary . '--' . $eol . $eol;
$request = new Request('files');
$request->method(HTTP_Request::POST);
$request->headers(array('Content-Type' => $contentType));
$request->body($data);
$request->execute();
答案 1 :(得分:0)
从GitHub找到a pull request讨论此事。我最终在控制器中添加了一些测试代码以解决问题:
if ($this->request->query('unittest'))
{
// For testing, don't know how to create internal requests with files attached.
// @link http://stackoverflow.com/questions/10988622/post-a-file-via-request-factory-in-kohana
$raw_file = file_get_contents(APPPATH.'tests/test_data/sample.txt');
}
Request::files()
方法会很好。