1

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();
esimran
  • 89
  • 2
  • 11

2 Answers2

0

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 = "\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();
Thomas Fussell
  • 458
  • 3
  • 9
  • Yep I got it from there. I would like to figure out how to get the requestFactory code working. It seems to be posting fine to the controller just not picking up the file. – esimran Jun 12 '12 at 19:06
  • I changed my answer to not use cURL. Maybe it's closer to what you're looking for. – Thomas Fussell Jun 12 '12 at 23:03
0

Found a pull request from GitHub that discusses the matter. I ended up adding some testing-code to my controller to get around the problem:

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');
    } 

A Request::files() method would be nice tho.

anroots
  • 1,959
  • 1
  • 14
  • 21