aimfeld
aimfeld

Reputation: 3141

Get file content from multipart data sent via rest request in ZF2

I need to retrieve the content of two files which I send to my ZF2 rest application using a POST request created with the Postman chrome extension. I specify the two files in the form-data dialog in postman, which are encoded in the request as follows (request preview):

...

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="blackbox-data"; filename="blackbox-data.txt"
Content-Type: text/plain


----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="assessment-configuration"; filename="assessment-configuration.xml"
Content-Type: text/xml

...

I have extended the ZF2 AbstractRestfulController to handle rest requests, which works fine. How can I get the file content of the two files sent from within MyRestController::create()?

I have tried the following, but all I get are empty arrays, empty strings:

$meta = $this->request->getMetadata();
$content = $this->request->getContent();
$blackboxData = $this->request->getPost('blackbox-data');
$assessmentConfiguration = $this->request->getPost('assessment-configuration');

Upvotes: 2

Views: 1600

Answers (1)

lluisaznar
lluisaznar

Reputation: 2393

You have to use the $request->getFiles(). I do it this way:

$validFiles = array();
$data = $request->getPost()->toArray();
$postFiles = $request->getFiles();

foreach ($postFiles as $key => $file) {
    if ($file['error'] == UPLOAD_ERR_NO_FILE) continue;

    $validFiles[$key] = $file;
}

if (count($validFiles)) $data['files'] = $validFiles;

And now I have an array called $validFiles, with the successfully uploaded files, in the $data array (where I store all the post data).

Upvotes: 3

Related Questions