PHP and Javascript - File Upload Help

Asked

Viewed 323 times

1

I have on my client’s website, which I took over from another developer, a section on the registration of meetings and events. In this section, I need to implement a PDF file upload field related to the event/meeting to be registered.

I tried to implement based on other sections of the site that had already been developed and that have uploaded files as well. But I still could not make this upload work. Follow the code below:

HTML

        <table>
        <tr>
            <td><b>{label_cadadmin_reunioes_unidade}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>                
                <select id="selectUnidade">     
                    <!-- BEGIN BLOCK_UNIDADES -->
                    <option value="{OBJ->ID}">{OBJ->NOME}</option>
                    <!-- END BLOCK_UNIDADES -->
                </select>
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_tipoinvestidor}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>
                <form>
                    <input type="radio" value="P" name="tipoInvestidor" id="poolOpt">{label_cadadmin_reunioes_poolista}
                    <input type="radio" value="C" name="tipoInvestidor" id="condOpt">{label_cadadmin_reunioes_condomino}
                </form>
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_tipoevento}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>
                <select id="selectTipoEvento">      
                    <option value="1">{label_cadadmin_reunioes_rcc}</option>
                    <option value="2">{label_cadadmin_reunioes_ago}</option>
                    <option value="4">{label_cadadmin_reunioes_age}</option>
                </select>           
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_datainicial}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td><input id="dataInicialReuniao" class="dadosInputG" type="text" value=""></td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_horainicial}:</b>&nbsp;</td>
            <td><input id="horaInicialReuniao" class="dadosInputG" type="text" value=""></td>
        </tr>
        <tr>
            <td><b>Anexar Arquivo:</b>&nbsp;</td>
            <td>
                <span class="retornodadospessoais">
                <input id="anexoReuniao" type="file" size="30" class="dadosTypeFile" name="anexoReuniao">
                </span>
                <iframe name="upload_iframeReuniao" id="upload_iframeReuniao" style="display:none;"></iframe>

            </td>
        </tr>
    </table>

JAVASCRIPT (with functions open)

function abrirModalReunioesEventos(){
var close = $('#lblCancelar').val();
var save = $('#lblSalvar').val();
var dialog_buttonsReuniao = {};  

dialog_buttonsReuniao[close] = function(){ 
    $( this ).dialog( "destroy" );
    //window.location = location.href.split("?")[0]+"?menu=reunioesEventos";

    $("#selectUnidade").val($("#selectUnidade  > option:first-child").val());
    $('#poolOpt').removeAttr('checked');
    $('#condOpt').removeAttr('checked');
    $("#selectTipoEvento").val($("#selectTipoEvento  > option:first-child").val());
    $('#dataInicialReuniao').val('');
    $('#horaInicialReuniao').val('');
    $('#anexoReuniao').val('');
};
dialog_buttonsReuniao[save] = function(){
    cadastroNovoEvento();
};

$('#modalCadastraNovaReuniao').attr('title',$('#lblTitleCadastrarReuniao').val());
$('#modalCadastraNovaReuniao').dialog({
    width: 710,
    modal: true,
    autoOpen: false,
    resizable: false,
    closeOnEscape: true,
    position: 'top',
    buttons: dialog_buttonsReuniao,
    close: function(){
    }
});

$('#horaInicialReuniao').mask('99:99');
//definição da lingua dos datepickers
$.ajax({
      cache:false, 
      url: '[:raiz]cadAdmin/getLang',
      dataType: 'json',
      type: 'POST',
      success: function(data) {
            if(data!='eng'){
                var formato="yy/mm/dd"
            }else{
                var formato="dd/mm/yy"
            }
            $( "#dataInicialReuniao" ).datepicker({ 
                dayNamesMin: [$('#lblDom').val(), $('#lblSeg').val(), $('#lblTer').val(), $('#lblQua').val(), $('#lblQui').val(), $('#lblSex').val(), $('#lblSab').val()],  
                monthNames: [$('#lblJan').val(),$('#lblFev').val(),$('#lblMar').val(),$('#lblAbr').val(),$('#lblMai').val(),$('#lblJun').val(),$('#lblJul').val(),$('#lblAgo').val(),$('#lblSet').val(),$('#lblOut').val(),$('#lblNov').val(),$('#lblDez').val()], 
                dateFormat: "dd/mm/yy" //formato
            });
      }
});
$('#modalCadastraNovaReuniao').dialog('open');
}

function cadastroNovoEvento() {
//Pega a data atual
var dataHoje = new Date();
dataHoje.setHours(0); 
dataHoje.setMinutes(0); 
dataHoje.setSeconds(0); 
dataHoje.setMilliseconds(0);    

var ano = ($('#dataInicialReuniao').val()).substr(6,4);
var mes = ($('#dataInicialReuniao').val()).substr(3,2);
var dia = ($('#dataInicialReuniao').val()).substr(0,2);
var dataPrimeiro = new Date(ano,parseInt(mes)-1,dia);
dataPrimeiro.setHours(0); 
dataPrimeiro.setMinutes(0); 
dataPrimeiro.setSeconds(0); 
dataPrimeiro.setMilliseconds(0);

$("#obrigatorio").dialog({
    buttons : {
        Ok : function() {
            $(this).dialog('close');
        }
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

$("#criaEventoDataMaior").dialog({
    buttons : {
        Ok : function() {
            $(this).dialog('close');
        }
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

//Prepara a data para ser inserida em formato de banco
var datainicial = $('#dataInicialReuniao').val();
var substrdataini = datainicial.split('/');
datainicial = substrdataini[2]+'-'+substrdataini[1]+'-'+substrdataini[0]; //AAAA-MM-DD

//Verifica se a data inicial é menor que a data atual
if (($('#dataInicialReuniao').val()).length != 0) {
    if (dataHoje.getTime() > dataPrimeiro.getTime()) {
        $('#criaEventoDataMaior').dialog('open');
        return false;
    }
}

var horainicial = $('#horaInicialReuniao').val();
var substrhorainicial = horainicial.split(':');

if ($("form :radio").is(":checked") == 0) {
    $('#obrigatorio').dialog('open');
    return false;
} else if (($('#dataInicialReuniao').val()).length == 0) {
    $('#obrigatorio').dialog('open');
    return false;
}

$("#envioEventoOk").dialog( {
    buttons : {
        Ok : function() {
            showLoading();
            window.location = location.href.split("?")[0]+"?menu=reunioesEventos";
            $(this).dialog('close');
        } 
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

$("#erroExt").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            } 
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        }
    }); 
    $("#envioDocumentoErrorSize").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            }
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            hideLoading();
            $(".ui-dialog-titlebar-close").hide();
        }
    }); 

    $("#envioDocumentoError").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            } 
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        }
    });

var ext = $('#anexoReuniao').val().split('.').pop().toLowerCase();
var info = new Array();
info[0] = $('#lblInfoEv0').val();
info[1] = $('#lblInfoEv1').val();
info[2] = $('#lblInfoEv2').val();
info[3] = $('#lblInfoEv3').val();
info[4] = $('#lblInfo0').val();
info[5] = $('#lblInfoEv5').val();
info[6] = $('#lblInfoEv6').val();
info[7] = $('#lblInfoEv7').val();
info[8] = $('#lblInfoEv8').val();
info[9] = $('#lblInfoEv9').val();
info[10] = $('#lblInfoEv10').val();
info[11] = $('#lblInfoEv11').val();
info[12] = $('#lblInfoEv12').val();
info[13] = $('#lblInfoEv13').val();
info[14] = $('#lblInfoEv14').val();
info[15] = $('#lblInfoEv15').val();
info[16] = $('#lblInfoEv16').val();
info[17] = $('#lblInfoEv17').val();

$.ajax({
      async:true,
      cache:false, 
      url: '[:raiz]cadAdmin/cadastraNovoEvento',
      dataType: 'json',
      data: ({
          idunidade: $('#selectUnidade').val(),
          tipoinvestidor: $("input[name='tipoInvestidor']:checked").val(),
          tipoevento: $('#selectTipoEvento').val(),
          datainicial: datainicial,
          horainicial: $('#horaInicialReuniao').val(),
          anexoReuniao: $('#anexoReuniao').val()
      }),
      type: 'POST',
      success: function(data) {
          $("#envioEventoOk").dialog('open');
          $.ajax({
              async:true,
              cache:false, 
              url: '[:raiz]cadAdmin/enviaEmailEvento',
              dataType: 'json',
              data: ({
                  idunidade: $('#selectUnidade').val(),
                  tipoinvestidor: $("input[name='tipoInvestidor']:checked").val(),
                  tipoevento: $('#selectTipoEvento').val(),
                  datainicial: datainicial,
                  horainicial: $('#horaInicialReuniao').val(),
                  info: info
              }),
              type: 'POST',
              success: function(data) { 
              },
              error: function(data) {
              }
          });
      }
});
}

CONTROLLER (registered functionNoveEvento, called in Javascript)

public function cadastraNovoEvento() {
    //Puxa dados da função cadastroNovoEvento() no js
    $idunidade = $_POST['idunidade'];
    $tipoinvestidor = $_POST['tipoinvestidor'];
    $tipoevento = $_POST['tipoevento'];
    $datainicial = $_POST['datainicial'];
    $horainicial = $_POST['horainicial'];

    // TODO 18/11 - Novo teste de upload de PDF
    $anexo = $_FILES['anexoReuniao']['name']; // TODO Campo novo de cadastro no banco
    $erro = $_FILES['anexoReuniao']['error']; //Detecta erros no upload / Retorna 1 se o tamanho da imagem for maior do que é permitido pelo server
    $size = $_FILES['anexoReuniao']['size'];
    if ($erro != '1' AND $size < 4194304){
        $name = utf8_decode(str_replace("&","",$_FILES['anexoReuniao']['name']));

        $namefile = 'anexosreunioeseeventos/'.$name/*.'.'.$ext*/;

        $file_folder = Config::retorna('application', 'filepath_anexosreunioeseeventos');           

        move_uploaded_file($_FILES['anexoReuniao']['tmp_name'], $file_folder.'/'.$name);

        $name = utf8_encode($name);

        $namefile = 'anexosreunioeseeventos/'.$name/*.'.'.$ext*/;

        CadAdmin::salvaNovoEvento($idunidade, $tipoinvestidor, $tipoevento, $datainicial, $horainicial, $anexo, $namefile/*, $descricao*/);         

        echo '<p>0</p>';
    } else {            
        echo '<p>1</p>';
    }

    echo json_encode(1);
}

MODEL (Salvanovoevento function called in Controller):

public function salvaNovoEvento($idunidade, $tipoinvestidor, $tipoevento, $datainicial, $horainicial, $anexo, $namefile) {      
    //COLOCA NO BANCO
    $id_usuario = Login::retornaIdUser();

    if ($horainicial==''){
        $sql = "INSERT INTO evento(id_unidade, data_ini, tipo_evento, ind_tipo_investidor, id_usuario, caminho_anexo, nome_anexo) VALUES ";
        $sql .= "($idunidade, '$datainicial', $tipoevento, '$tipoinvestidor', $id_usuario, '$namefile', '$anexo')";
    }else {
        $sql = "INSERT INTO evento(id_unidade, data_ini, hora_ini, tipo_evento, ind_tipo_investidor, id_usuario, caminho_anexo, nome_anexo) VALUES ";
        $sql .= "($idunidade, '$datainicial', '$horainicial',  $tipoevento, '$tipoinvestidor', $id_usuario, '$namefile', '$anexo')";
    }
    System::element('db')->query($sql);
}

I believe there would be some adjustment missing in the Javascript part. Does anyone know what it might be?

  • I believe that in your ajax request it would be necessary to add the attribute contentType: multipart/form-data, since you intend to send a file

  • @jbrunoxd It didn’t work, it’s still the same.

  • But what mistake do you get?

  • @gustavox I don’t get error warning, just don’t insert the meeting/event and don’t write to the database (which is what the function originally does).

  • Browser inspector shows no error in JS? Tries to put error_reporting(E_ALL); ini_set("display_errors", 1); in PHP files (models and controler), right at the beginning, after <?php and see if there are any errors...

  • 1

    managed to solve?

  • @durtto I did. Thank you

  • How nice you got a correct answer?

  • @durtto I went another way, but thanks for your attention.

  • So you need to put the answer here.

  • Here questions cannot go unanswered.

Show 6 more comments

1 answer

-1

Try it this way:

In HTML puts a form surrounding all your inputs <form id="umaIdQualquer" enctype="multipart/form-data">

And in your javascript add this before ajax

var formData = new FormData($("#umaIdQualquer")[0]);
$.ajax({

In the ajax date field do so: data: formData

$.ajax({
    // .... seu código
    data: formData
    // .... seu código
});

I believe this way you can already get the file via $_FILES.

Just remembering that Formdata is part of the Html5 API, so it won’t work in older versions of browsers.

  • The HTML part was quiet. But the javascript part didn’t help, I think he didn’t recognize the variable formData as data.

  • Give a console.log in formData before ajax.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.