Error while uploading files

Asked

Viewed 50 times

0

I want to upload files, where I insert the file name into the database and the file into a folder on the server.

I’m trying this way:

HTML:

<form class="form5" method="post" enctype="multipart/form-data">
<div class="row clearfix">
<span class="btn fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add Arquivo...</span>
<input type="file" id="arquivo" name="arquivo">
</span>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-success" id="mensagem-sucesso" onclick="inserir_anexos()">Gravar</button>
</div>

JS:

function inserir_anexos()
{  
    var dadosajax = {
        'CodigoUtente' : $("#CodigoUtente6").val(),
        'arquivo' : $("#arquivo").val()
    };
    $.ajax({
        url: './recebe_upload',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
            Swal.fire("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
        },
        success: function(result)
        { 
            $('.form5')[0].reset();
            Swal.fire('Boa!', 'Gravado com sucesso!', 'success');
        }
    });
}

PHP got this way:

$CodigoUtente = mysqli_real_escape_string($conn, $_POST["CodigoUtente"]);
$Colaborador = $_SESSION['usuarioId'];
$pathToSave = "/var/www/html/wp-content/themes/sparkling/alimentacao";

if (!file_exists($pathToSave)) {
    mkdir("$pathToSave", 0777);
}

   if ($_POST['arquivo']) { 
        $dir = $pathToSave; 
        $tmpName = $_POST['arquivo']['tmp_name']; 

        $name = $_POST['arquivo']['name'];
        preg_match_all('/\.[a-zA-Z0-9]+/', $name, $extensao);
        if (!in_array(strtolower(current(end($extensao))), array('.txt', '.pdf', '.doc', '.xls', '.xlms'))) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');
           
            die;
        }

       if (move_uploaded_file($tmpName, $dir.$name)) { 
            echo('Arquivo adicionado com sucesso.');
        } else {
            echo('Erro ao adicionar arquivo.');
        }   


           $query = 'INSERT INTO raddb.UploadArquivo(CodigoUtente, arquivo, Colaborador)  
           VALUES ( ?, ?, ?)';
           $stmt = $conn->prepare( $query );
           $stmt->bind_param("sss", $CodigoUtente, $name, $Colaborador);
           $stmt->execute();    
    }  

But when I record I get this message on the console:

Allowed only doc,xls, pdf and txt files.

And I’m making insert of a pdsf as I show in the image:

inserir a descrição da imagem aqui

And in the browser console the file name is also sent, as shown in the image:

inserir a descrição da imagem aqui

But neither insert into the database nor store the pdf file in the specified folder.

Can help?

3 answers

1

"or insert into the database or store the pdf file in the specified folder" Yes, because of the die it for processing and does not insert. This validation can be simpler, so try instead preg_match_all and a regex:

$permitidos = array('txt', 'pdf', 'doc', 'xls', 'xlms');
$name = $_POST['arquivo']['name'];
$extensao = pathinfo($name, PATHINFO_EXTENSION);
if (!in_array($extensao, $permitidos)) {
    echo('Permitido apenas arquivos doc,xls,pdf e txt.');

    die;
}
  • I changed that part of the code, but continues to stop processing on the die

  • yes, but that is expected correct? if the extension is not allowed should stop there, otherwise it will insert an invalid file. Does uploading a file with a valid extension work? In my reply the input name was wrong, see if you are testing with this code that is now pf

  • I am uploading a file with the PDF extension, it is a valid extension, but processing forever in die.

  • @Ricardopunctual, pathinfo() returns the file extension without the point what does co what always falls inside the 'if'

  • you’re right @Augustovasques, I tested here and I was with this problem... I copied this code from a page here, but I pasted the array that was in the question and I didn’t notice it, I will update the answer

1

You’re making a mistake because $_POST['arquivo'] returns a string obtained with the element <input type="file" id="arquivo" name="arquivo"> and when it does...

  • $tmpName = $_POST['arquivo']['tmp_name'];

  • $name = $_POST['arquivo']['name'];

...so much $tmpName and $name are undefined.

if ($_POST['arquivo']) { 
        $dir = $pathToSave; 
        $name = $_POST['arquivo'];
        // Não estou certo que temp seja uma pasta do cliente, acredito que deva ser o endereço de uma pasta dentro do servido mas a pergunta não deixa claro.
        $tmpName = pathinfo($name, PATHINFO_DIRNAME);

        // PATHINFO_EXTENSION retorna a extensão sem o ponto
        $extensao = pathinfo($name, PATHINFO_EXTENSION);
        if (!in_array($extensao, ['txt', 'pdf', 'doc', 'xls', 'xlms'])) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');

            die;
        }

        // continue com o seu código a partir desse ponto

1

The problem was sending the data on ajax. To solve my problem, I changed the js. Thus the variable arquivo is no longer sent as string, but how file

$(document).ready(function (e) {
 $(".form5").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "./recebe_upload",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data)
      {
    if(data=='invalid')
    {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    }
    else
    {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#arquivo").val(""); 
     $("#dataModal5").modal("hide");     
    }
      },
     error: function(e) 
      {
    $("#err").html(e).fadeIn();
      }          
    });
 }));
});

and in php was like this:

$codigo = $_POST['CodUtente'];
$Colaborador = $_SESSION['usuarioId'];

$pathToSave = "/var/www/html/wp-content/themes/sparkling/arquivo_psicologia/";

if (!file_exists($pathToSave)) {
    mkdir("$pathToSave", 0777);
}
if ($_FILES) {
   if ($_FILES['arquivo']) { 
        $dir = $pathToSave; 
        $tmpName = $_FILES['arquivo']['tmp_name']; 

        $name = $_FILES['arquivo']['name'];
        preg_match_all('/\.[a-zA-Z0-9]+/', $name, $extensao);
        if (!in_array(strtolower(current(end($extensao))), array('.txt', '.pdf', '.doc', '.xls', '.xlms'))) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');

            die;
        }

       if (move_uploaded_file($tmpName, $dir.$name)) { 
            echo('Arquivo adicionado com sucesso.');
        } else {
            echo('Erro ao adicionar arquivo.');
        }   


           $query = 'INSERT INTO raddb.UploadArquivo(CodigoUtente, arquivo, Colaborador)  
           VALUES ( ?, ?, ?)';
           $stmt = $conn->prepare( $query );
           $stmt->bind_param("sss", $codigo, $name, $Colaborador);
           $stmt->execute();    
    }
}

Browser other questions tagged

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