Problem uploading ajax and php files

0

I do not know what is happening but I can not upload files with php / ajax does not recognize the index file, My code:

Html:

<div class="wrapper-attachment" data-type="attachment" style="display: none;">
  <form name='archivo' enctype="multipart/form-data" class='formulario'>
    <input type="file" class="hidden inputAttachment"/>
  </form>
  <div class="buttonAddAttach">
    <div class="img-wrapper buttonImage">
      <i class="icon-cloud-upload"></i>
    </div>
    <span class="buttonText">Subir archivo</span>
  </div>
</div>

JS:

$(document).on('change','.inputAttachment',function(e){
  var formData = new FormData($(this).parent()[0]);
  $.ajax({
    url: base_url + 'Task/upAttach',
    type: "POST",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success:function(e){
      alert("exito");
      console.log(e);
    },
    error:function(e){
      alert("error");
      console.log(e);
    }
  });
});

PHP:

public function upAttach(){

  if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
     strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
  {

    //obtenemos el archivo a subir
    $file = $_FILES['archivo']['name'];

    //comprobamos si existe un directorio para subir el archivo
    //si no es así, lo creamos
    if(!is_dir("files/")) 
    mkdir("files/", 0777);

    //comprobamos si el archivo ha subido
    if ($file && move_uploaded_file($_FILES['archivo']['tmp_name'],"files/".$file))
    {
      sleep(3);//retrasamos la petición 3 segundos
      echo $file;//devolvemos el nombre del archivo para pintar la imagen
    }
  }else{
    throw new Exception("Error Processing Request", 1);   
    echo ("error");
  }
}
    
asked by Korzan 21.07.2017 в 14:31
source

2 answers

1

The errors in your code are:

  • The <input type="file" does not have name .
  • The <form has the name that the input should have

Solution:

Modify your markup in the following way:

<form enctype="multipart/form-data" class='formulario'>
  <input name="archivo" type="file" class="hidden inputAttachment"/>
</form>
    
answered by 21.07.2017 в 18:07
0

If you print in JavaScript console the content of your variable formData is probably empty. As far as I remember JQuery does not include files in its ajax methods.

I'm taking the example of here and adapting it to your case; do not forget to name the input of the file since in the original code it does not have a name:

var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event){
 files = event.target.files;
}

$('form_archivo').on('submit', uploadFiles);

function uploadFiles(event){
  event.stopPropagation();
  event.preventDefault();
  var data = new FormData();

$.each(files, function(key, value){
    data.append(key, value);
  });

  $.ajax({
    url: base_url + 'Task/upAttach',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function(data, textStatus, jqXHR){
      if(typeof data.error === 'undefined'){
        submitForm(event, data);
      } else {
        console.log('ERRORS: ' + data.error);
      }
    }, error: function(jqXHR, textStatus, errorThrown){
      console.log('ERRORS: ' + textStatus);
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='archivo' id="form_archivo" enctype="multipart/form-data" class='formulario'>
  <input type="text" name="texto" placeholder="escribe algún texto"><br />
  <input type="file" name="files" class="hidden inputAttachment"/><br />
  <input type="submit">
</form>
<br />
<div class="buttonAddAttach">
  <div class="img-wrapper buttonImage">
    <i class="icon-cloud-upload"></i>
  </div>
  <span class="buttonText">Subir archivo</span>
</div>

In your PHP code you can initially do exit(var_dump($_FILES)); to know that you are actually sending files.

    
answered by 21.07.2017 в 15:32