美文网首页
Upload mutilpe files to PHP, AJA

Upload mutilpe files to PHP, AJA

作者: 严瑞斌 | 来源:发表于2016-06-24 12:44 被阅读0次

    In client side:

    HTML:

    <form id="FILEFORM" enctype="multipart/form-data">
        <input id="FILE" name="ADDFILE[]" type="file" onchange={this.handleFiles} multiple/>
    </form>
    

    The magic key here is to set the name "ADDFILE[]". Without "[]", the PHP side will only receive single file.
    Also we need to add multiple to <input>.

    Javascript:

    var formData = new FormData($('#FILEFORM')[0]);
    /* equivalent to above code. But in this way we can rename file names for ever files we selected.
    var formData = new FormData();
    $.each( $('#FILEFORM').find('input')[0].files, function( i, file ){
        formData.append('ADDFILE', file );
    });
    */
    $.ajax({
        url: 'mod.php',  //Server script to process data
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false //dont process since it's formdata.
    })
    

    $('#FILEFORM')[0] means get the original javascript DOM with Jquery because we need it for formData.

    PHP:

    $total = count( $_FILES['ADDFILE']['name'] );
    for ( $i = 0; $i < $total; $i ++ )
    {
        ... // process data..
    }
    

    The key here is to get the file with name ADDFILE which we defined in HTML <input> attr name.

    相关文章

      网友评论

          本文标题:Upload mutilpe files to PHP, AJA

          本文链接:https://www.haomeiwen.com/subject/kdpodttx.html