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

Posted on

Question :

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();

                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.


Answer :

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] );

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

Another answer worth just looking at Gabriel Gartz


Leave a Reply

Your email address will not be published. Required fields are marked *