dqy13020940 2012-06-11 23:03
浏览 32

通过Kohana的Request Factory发布文件

Is it possible to simulate a file upload request in Kohana 3.2? I was trying the following but not having much luck:

$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();
  • 写回答

2条回答 默认 最新

  • dongtangu8403 2012-06-12 01:29
    关注

    This Kohana forum post indicates that it should be possible. Given the similarity to your code, I'm guessing you already found that. As that's not working for you, you could try 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);
    

    If you want to use the Kohana Request, you could try building your own multipart body using this code (I don't have the proper setup to test it right now, but it should be close to what you need):

    $boundary = '---------------------' . substr(md5(rand(0,32000)), 0, 10);
    $contentType = 'multipart/form-data; boundary=' . $boundary;
    $eol = "
    ";
    $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();
    
    评论

报告相同问题?