0

I am trying to upload an image file to the server, but the $_FILE is always empty and I don't know why.

Here is the html:

    <form action='' id='ajax_form' method='post' enctype="multipart/form-data">
      <input type='file' name='imagem'>
      <input type='submit' id='btUploadImagem' value='Upload'>
    </form>

And here the jquery script:

    function salvaImagem(){

    var form = $(this).closest('form'); 
    var formData = new FormData(form);
    var dados = formData;
    jQuery.ajax({
        type: "POST",
        url: "salvaImagem",
        data: dados,
        contentType: false,
        processData: false,
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){
                //show success message
            }
            else{
                //show error message
            }
        });
    return false;
}

$('#btUploadImagem').on('click', salvaImagem); 

And the controller php:

    public function salvaImagem()
    {   
       $arquivo = isset($_FILES["imagem"]) ? $_FILES["imagem"] : FALSE;
       //some other checks
    }

What am I doing wrong so the $_FILE is always empty?

Carlos Ost
  • 432
  • 5
  • 19
  • dataType: "json" ?? try taking that out as a test. if none is specified, jQuery will try to infer it based on the MIME type of the response – Tasos Apr 14 '16 at 01:52
  • Similar http://stackoverflow.com/questions/36609643/image-upload-with-ajax-but-php-does-not-see-file – Musa Apr 14 '16 at 01:58

2 Answers2

0

I suggest you to use a plugin for manage upload. Try use Jquery Plupload

But if you dont want use a plugin, try print_r($_FILES, true) to see if any informations are there

0

Have you tried dados.append(name, value, filename);? Check https://developer.mozilla.org/en-US/docs/Web/API/FormData/append for details. I'm unfamiliar with the FormData Web API myself. You might also find your answer here: How to use FormData for ajax file upload

Community
  • 1
  • 1
Mark Priddy
  • 486
  • 7
  • 15