ajax multiple file upload with php

后端 未结 2 1910
半阙折子戏
半阙折子戏 2021-01-14 06:21

Hey I am uploading files to a chosen folder and right now I have the ability to select and upload just one file. I know how to handle multiple files in php but I am not sur

相关标签:
2条回答
  • 2021-01-14 07:00

    First you have to use "multiple" attribute with input tag. Like

    <input id="fileUpload" type="file" accept="image/*" name="my_file[]" multiple />
    

    Then in Javascript onChange function -

            var data = new FormData();
            var imgData = document.getElementById('fileUpload'); 
    
            for (var i = 0; i < imgData.files.length; i++) {                                 
                 data.append('my_file[]', imgData.files[i], imgData.files[i].name);
            } 
    
           //now call ajax
           $.ajax({
              url: "upload.php",
              type: "POST",
              data: data,
              enctype: 'multipart/form-data',
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
                alert("upload success!")
            });
    

    And your file will be uploaded

    0 讨论(0)
  • 2021-01-14 07:08

    You can pass multiple files using form data as below

    HTML

    <input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
    

    JS

    var fd = new FormData();
    var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
    fd.append("label", "sound");
    
    for (var i = 0; i < files.length; i++) {
        fd.append("UploadedImage" + i, files[i]);
    }
    
    $.ajax({
        type: "POST",
        url: 'Url',
        contentType: false,
        processData: false,
        data: fd,
        success: function (e) {
            alert("success");                    
        }        
     })
    

    Now pass fd object in you ajax call it is working with my code

    0 讨论(0)
提交回复
热议问题