【问题标题】:Post a file via Request Factory in Kohana通过 Kohana 的 Request Factory 发布文件
【发布时间】:2012-06-11 23:03:48
【问题描述】:

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

【问题讨论】:

    标签: php kohana kohana-3.2


    【解决方案1】:

    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 请求,您可以尝试使用此代码构建自己的多部分主体(我现在没有适当的设置来测试它,但它应该接近您的需要):

    $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();
    

    【讨论】:

    • 是的,我从那里得到它。我想弄清楚如何让 requestFactory 代码工作。它似乎可以很好地发布到控制器,只是没有拾取文件。
    • 我将答案更改为不使用 cURL。也许它更接近您正在寻找的东西。
    【解决方案2】:

    从讨论此事的 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() 方法会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2016-05-14
      • 2017-01-18
      • 1970-01-01
      相关资源
      最近更新 更多