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 php , 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 ajax :
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;
}