phpfileuploadsilexmustache.php

PHP Form - Uploading Files, wanting to use Silex but not FormBuilder


I'm using Silex to build an app, though it's not the typical Silex setup.

I've got Mustache as the templating engine.

I'm not using Doctrine for ORM / DBAL, I'm using Capsule (Silex-Eloquent), and am having some serious trouble wrapping my head around this.

Currently I have a form:

<form class="form-horizontal" role="form" action="app.php/listing" method="POST" id="listing-submit">

            <div class="form-group">
                <label class="control-label col-sm-2" for="title">Listing Title</label>

                <div class="col-sm-6">
                    <input id="title" class="form-control" type="text" size="40" autocomplete="off"
                           data-encrypted-name="title"/>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-sm-2" for="description">Description</label>

                <div class="col-sm-6">
                    <textarea id="description" class="form-control" rows="8"></textarea>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-sm-2">Images</label>

                <div class="col-sm-6">
                    <input type="file" name="images[]" id="images" multiple/>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-6">
                    <button type="submit" class="btn btn-default">Submit</button>
                </div>
            </div>

        </form>

Which I'm using to select files, though, all the examples I've seen thus far of Silex and file uploading, uses something I'm not to familiar with, and not sure I can make it adapt to my use: The FormBuilder, FormBuilderInterface, registering custom types and all that jazz...

This is the Controller-Part so far:

$app->post("/plisting", function () use ($app) { 

  // $params = $request->all(); 
  $request = $app['request']; 
  $title = $request->get('title'); 
  $description = $request->get('description'); 
  $image = $request->files->get('image'); 

  // $file->move(__DIR__ . '/files', $file->getClientOriginalName()); // return "done"; 

  return "<pre>Class for request: " . get_class($request) . "<br>Title: $title <br>Description: $description<br>File: $image </pre>"; 
});

Note, I'm using ajax to handle to file uploads.

I'm curious if someone is able to walk me through using the setup in place and silex to upload files, or if I should just use non-framework PHP to handle the file uploads?

I'm at a mental block here, and could use a hand; Thanks!


Solution

  • In order to send files to the server, the browser has to encode its data using multipart/form-data, so you should just try to add the attributeenctype='multipart/form-data' to your form (which currently is missing).

    See here for more information.