Pick up the name of an image by Php or JS

1

Well, I have a form that has a input of type ='file' . I've seen it on various websites and examples of how to do it and all that I testo do not work. the code I can not share more is more or less so.

I have a form with the input file and an input button on the Button button JS calls a function that takes the values from the form and does a array(JSON) , then does Ajax with PHP for insertion into bank.

Only the array when in PHO does not come with the name of the image. Blz then did direct in PHP like this: $img = $_FILES["arquivo"]["name"]; and it also returns empty the variable. Everything is correct form with enctype , but it does not work anyway.

Html:

<form action="?pagina=cadastroEmpresas" method="POST" id="formEmpresa" name="formEmpresa" enctype="multipart/form-data">
<input value="Salvar" id="btnSalvarForm" style="padding: 5px; font-size: 14px; margin-left: -13px;" type="button">
<label for="arquivo">Logo:</label> <input name="arquivo" id="arquivo" value="" type="file" />

JS:

$( "#btnSalvarForm" ).on("click", function() {
    inserirEmpresa();
});
function inserirEmpresa(){
    campos = pegarCampos( "formEmpresa" );
    $.ajax({
        type : "POST",
        data : {dados:JSON.stringify(campos)},
        url : "php/buscaEmpresasBD.php?escolha=7",
        success : function(resposta){
            alert(resposta);
            $("#divCamposForm").css("display", "none");
        }//fim success      
    });//fim ajax
}

PHP:

function inserirEmpresa(){
        global $cnx;
        //echo $_POST['dados'];
        $dados = json_decode($_POST['dados'], TRUE);
        //echo $dados["txtNomeFantasiaEmpresa"];
        $target_dir = "galeria/";
        //$target_file = $target_dir . basename($_FILES["arquivo"]["name"]);
        $target_file = $target_dir . basename($_FILES["arquivo"]["name"]);
        echo "$target_file";
}
    
asked by anonymous 23.09.2015 / 14:32

1 answer

0

If you are using ajax , file does not upload by ajax . But there are some methods that will work.

Some questions about this:

link
Upload file with AJAX

But if you want to get the name (not the file) - from the file by JS (jQuery) do so:

$('.file').on('change', function(){

    // Pega o Nome do Arquivo
    var fileName = $('input[type="file"]')[0].files[0].name;

    // Coloca num campo Hidden com ID #file-name
    $('#file-name').val(fileName);

});
    
23.09.2015 / 14:44