send file by ajax

Asked

Viewed 82 times

0

I have a form to fill and record files in the database passing the data by ajax but the file is not coming.

The form:

<script src="jquery.min.224.js"></script>
$("#documento").click(function(e) {
  e.preventDefault();
  var text1  = $("#arqnome").val();
  var text2  = $("#arq").val();
  $.ajax({
      type: "POST",
      url: "arquivo.php",
      data: { documento: $(this).val(), arqnome: text1, arq: text2 }
  })
  .done(function(data){
      $("#documento_e").html(data);
      //$("#form")[0].form.reset();
  });    
});
<form id="form_docs" method="post" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tbody>
          <tr>            
            <td>
            Tipo de Arquivo:<br />
            <input type="text" name="arqnome" id="arqnome">              
            </td>
            <td>
            Selecionar Arquivo:<br />
            <input type="file" name="arq" id="arq">
            </td>
            <td>
            <button type="button" id="documento" name="documento">Gravar</button>
            </td>
          </tr>
        </tbody>
      </table>
</form>
<div id="documento_e"></div>

The page that processes the data:

include("banco.php");
if(isset($_POST['documento'])){
        $img = $_FILES["arq"]["name"];  
        $ext = strtolower(strrchr($img, '.'));  
        $imgn = str_replace($_POST['arqnome'],' ','_').$ext; 
        $dest = $imgt . '_tmp/' . $imgn;        
        move_uploaded_file( $_FILES['arq']['tmp_name'], $dest );

        pg_query($dbconn, "begin");
        $oid = pg_lo_import($dbconn, $imgt . '_tmp/' . $imgn);
        $sql = "insert into tabela(arqnome, arq, arqext) values('".$_POST['arqnome']."', '$oid', '$ext'");
        $res = pg_query($dbconn,$sql);
        pg_query($dbconn, "commit");

        unlink($imgt . '_tmp/' . $imgn);
}
  • See his reply at this link: https://answall.com/questions/9704/fazer-upload-de-archivalcom-ajax

2 answers

2


  1. Missing variable $imgt
  2. ajax is sending data incorrectly: with data:.... arqnome: text1 php recovers using $_POST and not with $_FILES
  3. str_replace is wrong

HTML + AJAX

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        // evento de "submit"
        $("#documento").click(function (e) {
            // parar o envio para que possamos faze-lo manualmente.
            e.preventDefault();
            // captura o formulário
            var form = $('#form_docs')[0];
            // cria um FormData {Object}
            var data = new FormData(form);
            // desabilitar o botão de "submit" para evitar multiplos envios até receber uma resposta
            $("#documento").prop("disabled", true);
            // processar
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: "arquivo.php",
                data: data,
                processData: false, // impedir que o jQuery tranforma a "data" em querystring
                contentType: false, // desabilitar o cabeçalho "Content-Type"
                cache: false, // desabilitar o "cache"
                // manipular o sucesso da requisição
                success: function (data) {
                    $("#documento_e").html(data);
                    // reativar o botão de "submit"
                    $("#documento").prop("disabled", false);
                },
                // manipular erros da requisição
                error: function (e) {
                    $("#documento_e").html(e);
                    // reativar o botão de "submit"
                    $("#documento").prop("disabled", false);
                }
            });
        });
    });
</script>

<form id="form_docs" method="post" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tbody>
          <tr>            
            <td>
            Tipo de Arquivo:<br />
            <input type="text" name="arqnome" id="arqnome">              
            </td>
            <td>
            Selecionar Arquivo:<br />
            <input type="file" name="arq" id="arq">
            </td>
            <td>
            <button type="button" id="documento" name="documento">Gravar</button>
            </td>
          </tr>
        </tbody>
      </table>
</form>
<div id="documento_e"></div>    

PHP

<?php

if(isset($_POST)){

        $img = $_FILES['arq']['name'];
        $arqnome = $_POST['arqnome'];
        $imgt="pasta";

        $ext = strtolower(strrchr($img, '.'));  
        $imgn = str_replace(' ','_',$arqnome).$ext; 
        $dest = $imgt . '_tmp/' . $imgn;        

        if (move_uploaded_file( $_FILES['arq']['tmp_name'], $dest )) {
             echo "Upload efetuado com sucesso!"; 
        }  else {
             echo "Não foi possível realizar o upload, tente novamente";
        }


        //codigo
        //código

}
?>
  • Leo Caraciolo, the $imgt variable is actually the path of the folder that is in my source script and I didn’t change here by forgetting, and actually replace was in postgre mode. As for the script, it worked fine. Thank you

0

No JS is missing the "action: 'nameFuncaoPHP'" In PHP is missing the Function that will receive this data.

Browser other questions tagged

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