How to get a file in PHP passed by $ .ajax?

4

I have a problem I do not know if it is when sending in $ .ajax or catching with PHP.

It is not getting the $_FILES normal on the other side, it arrives as 'caminhofoto' => string 'C:\fakepath.jpg' (length=17) , gave var_dump($_POST) , however when trying to get the path and move to the directory it only mounts the path but does not get the file. p>

My JS:

var caminhofoto = $("input[name='caminhofoto']").val();

        $.ajax({
                url: '/add-data.php',
                type: 'POST',
                data: {
                    caminhofoto: caminhofoto
                }
            }).done(function (data) {
            
                console.log("Sucesso: " + data);
           
            });

And in PHP:

$img = "imgs/";
$caminhofoto = $img . basename($_FILES['caminhofoto']['name']);
$imgFileType = strtolower(pathinfo($caminhofoto, PATHINFO_EXTENSION));

$uploaddir = '/fotos/';
$obj->setPath($uploaddir . $caminhofoto );

Only you're saving only the path in the database without the file, it looks like it's going to fakepath it's not catching.

    
asked by anonymous 20.12.2018 / 15:12

1 answer

2

We discussed the question comments and found that the problem was occurring because of the way the value was being sent by ajax .

Using FormData to send the file it would be able to reach the goal as shown in the example below.

var formData = new FormData(),
    $inputFoto = $("input[name='caminhofoto']");

 formData.append('foto', $inputFoto.prop('files')[0] );

 $.ajax({
     url: '/add-data.php',
     type: 'POST',
     data: formData,
     success: function(data) {
         alert(data)
     },
     cache: false,
     contentType: false,
     processData: false,
});

Another answer worth just looking at Gabriel Gartz

    
20.12.2018 / 21:28