Alex G.
Alex G.

Reputation: 43

Im trying to upload files using ajax and symfony

I'm using Symfony 2.7

I got this form

<form name="Document" method="post" action enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" id="documento" name="Document[Ruta]" required="required">
    </div>
    <div class="col-md-3">
        <button type="button" onclick="saveDoc()" class="btn btn-success" data-dismiss="modal">Subir</button>
    </div>
</form>

and this ajax:

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        data: {'data': data},
        processData: false,
        contentType: false,
        cache: false
    });

}

with this symfony controller:

public function fileUpload(Request $request)
{
    $file = $request->files->get('doc')->getClientOriginalName;
    $user = $this->getUser();

    $filename = md5(uniqid()).'.'.$file->guessExtension();

    $request->files->get('doc')->move(
        $this->getParameter('upload_directory'),
        $filename
    );
    $document = new Document();
    $document->setRuta($filename);
    $document->setIdUser($user);
    $document->setFechaCreacion(new \DateTime("now"));
    $em = $this->getDoctrine()->getManager();
    $em->persist($document);
    $em->flush();

    return new JsonResponse(true);

}

But I get this error:

Notice: Trying to get property of non-object 500 Internal Server Error - ContextErrorException

I saw 235897 pages with file uploading with symfony and ajax, I cannot understand what is wrong in my code, can you guys help me please?

Upvotes: 4

Views: 5509

Answers (2)

NDZIE Patrick Joel
NDZIE Patrick Joel

Reputation: 1142

Change this

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        data: {'data': data},
        processData: false,
        contentType: false,
        cache: false
    });

}

To

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        data: data,
        processData: false,
        contentType: false,
        cache: false
    });

}

and in the controller

Change following line:

$file = $request->files->get('doc')->getClientOriginalName;

to:

$file = $request->files->get('doc');

Upvotes: 3

habibun
habibun

Reputation: 1630

change

$file = $request->files->get('doc')->getClientOriginalName;

to

$file = $request->files->get('doc');

Upvotes: 0

Related Questions