How to create a formData.append to be able to send inputs of type File?

1

I want to send a input type="file" from a form , to send all the data of my form I use the formData , which I created from scratch in order to capture each of the data that exists in my form and receive it on a page , on this page I can capture all the data that are in the form but not I can capture the file, I have the following:

JS

Function where you created the FormData:

function dataForm_Archivos(formulario){
    var nuevoFormulario = new FormData();   
    $(formulario).find(':input').each(function() {
        var elemento= this;
        //Si recibe tipo archivo 'file'
        if(elemento.type === 'file'){
            if(elemento.value !== ''){
               var file_data = $('input[type="file"]')[0].files;
               for (var i = 0; i < file_data.length; i++) {
                  nuevoFormulario.append(elemento.name, file_data[i]);
               }
            }            
         }
     }
}

function where the id of the form arrives and sent it through :

function registrarDocumentacion(formulario){

var datosForm = dataForm_Archivos(formulario);
var request = $.ajax({
    contentType: false,
    processData: false,
    data: datosForm,                         
    type: 'POST',
    url: 'url',
    beforeSend:function(){

     }

    });

    request.done(function(datos) { 

    });
 }

HTML

<form role="form" action='#?' id="registroDocumentacion" method="post">
<div class="row">
  <div class="col-md-12">
    <div class="form-group">
        <label class="control-label">Adjuntar Archivo</label>
        <input type="file" id="arcAdjunto"  name="arcAdjunto" class="filestyle" placeholder="Asunto" onchange="validarArchivo('#arcAdjunto');">
        <h5><small>Recuerde, los tipos de archivos permitidos son: png, gif, jpg, jpeg, docx, xls, xlsx, docs, pdf</small></h5>
    </div>
  </div>
</div>
 <div class="row">
        <div class="col-md-12 text-left m-t-20">
                <button type="button" class="btn btn-primary waves-effect waves-light" id="enviarDoc" > Enviar <i class="fa fa-send" aria-hidden="true"></i>   </button>
          </div>
    </div>
</form>


<script type="text/javascript">
   $('#enviarDoc').click(function(event) {
     registrarDocumentacion('#registroDocumentacion')
   });
</script>

UPDATE

I managed to do it this way

function dataForm_Archivos(formulario){
    var nuevoFormulario = new FormData();   
    $(formulario).find(':input').each(function() {
        var elemento= this;
        //Si recibe tipo archivo 'file'
        if(elemento.type === 'file'){
           if(elemento.value !== ''){
              for(var i=0; i< $('#'+elemento.id).prop("files").length; i++){
                  nuevoFormulario.append(elemento.name, $('#'+elemento.id).prop("files")[i]);
               }
            }              
         }
     }
  return nuevoFormulario;
}
    
asked by Alan 24.06.2016 в 01:35
source

2 answers

4

You can use for this the; FormData Objects, here I'll leave an example:

 var formData = new FormData();

 formData.append("archivoDelUsuario", fileInputElement.files[0]); //Aquí capturas el fileInput seleccionado por el usuario
 var archivoBlob = new Blob([content], { type: "text/xml"}); //creamos un archivo tipo blob
 formData.append("elArchivo", archivoBlob); //listo agregamos el archivo

This code was consulted and mostly extracted from the official documentation of Developer Mozilla

    
answered by 24.06.2016 в 02:01
1

In the example that you put your function dataForm_Archivos(formulario) seems to have the correct logic, except that it does not return anything (you need return nuevoFormulario; at the end of the function) since var nuevoFormulario = new FormData(); is local to the function (it does not exist outside of she); so var datosForm = dataForm_Archivos(formulario); really does not collect anything.

Try with:

function dataForm_Archivos(formulario){
    var nuevoFormulario = new FormData();   
    $(formulario).find(':input').each(function() {
        var elemento= this;
        //Si recibe tipo archivo 'file'
        if(elemento.type === 'file'){
            if(elemento.value !== ''){
               var file_data = $('input[type="file"]')[0].files;
               for (var i = 0; i < file_data.length; i++) {
                  nuevoFormulario.append(elemento.name, file_data[i]);
               }
            }            
         }
     }

    return nuevoFormulario;
}
    
answered by 24.06.2016 в 09:13