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?

2
  • 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 Commented Apr 14, 2016 at 1:52
  • Similar stackoverflow.com/questions/36609643/… Commented Apr 14, 2016 at 1:58

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

print_r($_FILE, true) is incorrect, it needs to be $_FILES.
Oups, my bad, im tired lol
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.