6
votes

I've problem with upload file from form to Symfony2 controller by ajax.

This is my form by client side:

var uploadFile = function() {
var content = "<form id='uploadFile' enctype='multipart/form-data' action='' method='post'>" +
        "<input id='file' type='file'/>" +
        "</form>";
$("#upload-dialog").html(content);
$("#upload-dialog").dialog({
    resizable: false,
    title: 'Dodaj załączniki do umowy',
    height: 300,
    width: 450,
    buttons: [
        {
            text: 'Wyślij',
            click: function() {
                var formData = new FormData();
                formData.append('file', document.getElementById('file').files[0]);
                $.ajax({
                   url: Routing.generate('employees_upload_attachment'),
                   data: formData,
                   enctype: 'multipart/form-data',
                   processData: false,
                   contentType: false,
                   success: function() {
                   },
                   error: function() {

                   }
                });
            }
        }
    ]
});

};

and this is my controller

    public function uploadAttachmentAction(Request $request) {
    $fileBag = $request->files;
    var_dump($fileBag);
}

When I try to show uploaded file I get an empty FileBag object:

object(Symfony\Component\HttpFoundation\FileBag)#12 (1) {
["parameters":protected]=> array(0) { } }

What could be wrong?

EDIT: I solved it.I added to jquery ajax parameters

cache: false, type: 'POST'

and everything is ok :)

1
Have you tried logging the value of document.getElementById('file').files[0]?colinD
Yes, It's looks good.math
I solved this problem. I added to ajax paramaters: cache: false and type: 'POST'. Now everything is ok :)math
I'm trying something similar, but with the validate the form, to ensure integrity in my data, can help me? my questionMarcius Leandro
@math Please answer your own question, or delete it. It's still showing up in the "unanswered" section. ThanksPaolo Stefan

1 Answers

0
votes

Adding ajax paramaters:

cache: false,
type: 'POST'

Solved problem.

Note: Answer is based on comment not mine because it is showing up in the "unanswered" section.