PHP and Javascript - Hosting and opening files in formats other than PDF

Asked

Viewed 60 times

1

I created on my client’s website a way to host presence list files at events. Here’s the code:

<b>Arquivo da lista de presença (PDF):</b>
<?php if($evento['arquivo'] == '1'){
    echo '<a href="http://meusite.com.br/upload/wt_eventos_lista_presenca/'.$evento['id'].'.pdf" target="_blank" style="color: red">Download</a><br>';
}
else {?>
    <form id="form<?php echo $evento['id']; ?>" action="hospedaarquivo?valor=<?php echo $evento['id']; ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="arquivo<?php echo $evento['id']; ?>" id="arquivo<?php echo $evento['id']; ?>" class="validate[required] text-input" accept="pdf" />
                <input type="submit" name="fileEnvia" value="Enviar Arquivo" style="cursor: pointer; width: 100px;" />
    </form>
<?php }?>

And the function that makes the file hosting is

public static function HospedaArquivo(){
    $nome = 'arquivo' . $_SESSION['idTemp'];
    if(isset($_FILES[$nome]))
    {
        date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

        $ext = strtolower(substr($_FILES[$nome]['name'],-4)); //Pegando extensão do arquivo
        $new_name = $_SESSION['idTemp'] . $ext; //Definindo um novo nome para o arquivo
        $dir = 'upload/wt_eventos_lista_presenca/'; //Diretório para uploads

        if(move_uploaded_file($_FILES[$nome]['tmp_name'], $dir.$new_name)){
            echo "<script>alert('Upload feito com sucesso!');</script>";
            $sql = Doctrine_Query::create()
            ->update('WtEducEventos')
            ->set('arquivo', '?','1')
            ->where('id = ?',$_SESSION['idTemp']);
            $sql->fetchArray();
        }
        else {
            echo "<script>alert('Erro no upload');</script>";
        }
    }
    else{
        echo "<script>alert('Não há arquivo selecionado');</script>";
    }
}

But I narrowed it down to the HTML part to accept PDF only to make it easier after downloading. If I want it to accept JPG, for example, how can I make it to check if the file is PDF or JPG? I do some other integration with the Mysql database (if you have the file, it is 1, if you do not have 0 the value of the field "file")?

1 answer

2

With Javascript, you can get the file type and check if it has the PDF or JPEG type using files[0].type at the event change of input :

document.getElementById("arquivo").addEventListener("change", function(ev) {
  var tipo = ev.target.files[0].type;
  document.getElementById("tipo").innerHTML = tipo;
  if (tipo.indexOf("jpeg") !== -1 || tipo.indexOf("pdf") !== -1) {
    console.log(tipo);
    alert("Arquivo válido")
  } else {
    alert("Arquivo inválido");
  }
})
<input id="arquivo" type="file" />
<br/>
<span id="tipo"></span>

  • I know you can put it in the Accept property like this: Accept="pdf, jpg". But to later do the file donwload I would have to change the code I made, which only accepts to see the file when it is PDF.

Browser other questions tagged

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