Send file by AJAX [duplicated]

2

I am trying to send a% file% by ajax , but the input file returns an error.

How can you send "file" files by PHP ?

THE HTML CODE

<form id="form" enctype="multipart/form-data">
    <input type="file" name="archivo" id="archivo">
    <p>
    <input type="submit" name="submit">
</form>

THE AJAX CODE

$(document).ready(function($) {
   //// METODO PARA INSERTAR LOS DATOS //// 
    $("#form").submit(function() {
        event.preventDefault();

        var cadena = $(this).serializeArray();

        $.ajax({
            url: 'php.php',
            type: 'POST',
            data: cadena
        })      
        .done(function(respuesta) {

            var resultado = $.parseJSON(respuesta);
            console.log(resultado);
        .fail(function() {
            console.log("error");
        });
});
});

THE PHP CODE

<?php
    $nombre = array($_POST['archivo']);
    echo json_encode($nombre);
?>
    
asked by JDavid 05.01.2017 в 20:46
source

2 answers

3

The input of type file goes to variable $_FILES

$nombre = $_FILES['file-0'];

about javascript you must do this

var data = new FormData();
jQuery.each($('input[type=file]')[0].files, function(i, file) {
    data.append('file-'+i, file);
});
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
    data.append(input.name,input.value);
});
jQuery.ajax({
    url: 'php.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});
    
answered by 05.01.2017 в 20:54
0

I would recommend you evaluate using FormData to send a file using ajax

Ajax File Upload with Form Data using PHP

As you will see in the example, assign the this when using

 data: new FormData(this),

something like being

   $.ajax({
        type: 'POST',
        url: 'submit.php',
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        .
        .
    
answered by 16.04.2018 в 23:15