Retrieve input file to pass as date in AJAX

0

I'm developing an application in which, for reasons of aesthetics, I needed to recreate some elements in order to be able to customize each one, especially <select> and <option> correctly.

So I need to pass the form by picking the date manually. For this, I'm using:

  $('#criarConta').click(function(){
    $.ajax({
    url: "empregador.php",
    type: "POST",
    data: {
      nome:       $('#nomeSign').val(),
      email:      $('#emailSign').val(),
      senha:      $('#passSign').val(),
      local:      $('#localInput').val(),
      site:       $('#siteInput').val(),
      tipo:       $('#tipoPerfil').data('selected'),
      ramo:       $('ramoInput').data('selected'),
      profilepic: $('profilePicInput').val()
    },
    contentType: false,
    cache: false,
    processData:false,
    success: function(data){
      console.log(data);
    }
    });
  });

I put this profilepic there to see where I want to call the image. As far as I know, .val() will only recover the file path, not itself.

How do I resolve my case?

    
asked by anonymous 17.01.2018 / 16:58

1 answer

2

To submit an image, you can use FormData . This is an API used to store values that will be sent via POST.

When you use this API, you're basically using enctype: multipart/form-data

But you need to know another point, this time with jQuery.ajax . By default, the jquery transforms the value from data to application/x-www-form-urlencoded , so you will have to inform that does not want to use this default.

When you are not working with sending files, legal, there are no problems, but in the case of uplaods it is necessary to add this information: processData:false,

Now let's talk about input. How to capture the file and not the fake path ?

Other than input:text , for example, input:file has one more attribute. The file attribute is responsible for storing in an array, all object files of type File within a FileList .

This object - file - is nothing more than a Blob (raw file ) and it will be sent to the server.

  

In the case of images, you can use this object to display a thumbnail or even #

$('#criarConta').click(function(){     
    let form = new FormData();
    form.append("nome", $("#nome").val());
    form.append("file", $('#imagem').prop('files')[0]);

    $.ajax({
        url: "index3.php",
        type: "POST",
        data: form,
        cache : false,
        processData: false
    });
});

Ah, and value , in input:file only displays C:\fakepath to prevent you from having access to the user's folder structure.

    
17.01.2018 / 17:48