1

是否可以在 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();
4

2 回答 2

0

这个 Kohana 论坛帖子表明它应该是可能的。鉴于与您的代码相似,我猜您已经发现了。由于这对您不起作用,您可以尝试 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 请求,您可以尝试使用此代码构建自己的多部分主体(我现在没有正确的设置来测试它,但它应该接近您的需要):

$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();
于 2012-06-12T01:29:25.030 回答
0

从 GitHub 上找到一个讨论该问题的拉取请求。我最终向我的控制器添加了一些测试代码来解决这个问题:

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()方法会很好。

于 2013-03-02T18:30:05.177 回答