복붙노트

[JQUERY] PHP, jQuery를하고 AJAX를 사용하여 여러 파일을 업로드하는 방법

JQUERY

PHP, jQuery를하고 AJAX를 사용하여 여러 파일을 업로드하는 방법

해결법


  1. 1.마지막으로 다음 코드를 사용하여 솔루션을 발견했다 :

    마지막으로 다음 코드를 사용하여 솔루션을 발견했다 :

    $('body').on('click', '#upload', function(e){
            e.preventDefault();
            var formData = new FormData($(this).parents('form')[0]);
    
            $.ajax({
                url: 'upload.php',
                type: 'POST',
                xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    return myXhr;
                },
                success: function (data) {
                    alert("Data Uploaded: "+data);
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
    });
    

  2. 2.HTML

    HTML

    <form enctype="multipart/form-data" action="upload.php" method="post">
        <input name="file[]" type="file" />
        <button class="add_more">Add More Files</button>
        <input type="button" value="Upload File" id="upload"/>
    </form>
    

    자바 스크립트

     $(document).ready(function(){
        $('.add_more').click(function(e){
            e.preventDefault();
            $(this).before("<input name='file[]' type='file'/>");
        });
    });
    

    아약스 업로드

    $('#upload').click(function() {
        var filedata = document.getElementsByName("file"),
                formdata = false;
        if (window.FormData) {
            formdata = new FormData();
        }
        var i = 0, len = filedata.files.length, img, reader, file;
    
        for (; i < len; i++) {
            file = filedata.files[i];
    
            if (window.FileReader) {
                reader = new FileReader();
                reader.onloadend = function(e) {
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("file", file);
            }
        }
        if (formdata) {
            $.ajax({
                url: "/path to upload/",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function(res) {
    
                },       
                error: function(res) {
    
                 }       
                 });
                }
            });
    

    PHP

    for($i=0; $i<count($_FILES['file']['name']); $i++){
        $target_path = "uploads/";
        $ext = explode('.', basename( $_FILES['file']['name'][$i]));
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
    
        if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
            echo "The file has been uploaded successfully <br />";
        } else{
            echo "There was an error uploading the file, please try again! <br />";
        }
    }
    
    /** 
        Edit: $target_path variable need to be reinitialized and should 
        be inside for loop to avoid appending previous file name to new one. 
    */
    

    아약스 업로드 스크립트 위의 스크립트를 사용하십시오. 그것은 작동합니다


  3. 3.내 솔루션

    내 솔루션

    jQuery 코드

    $('#my_form_id').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData($(this)[0]);
        var msg_error = 'An error has occured. Please try again later.';
        var msg_timeout = 'The server is not responding';
        var message = '';
        var form = $('#my_form_id');
        $.ajax({
            data: formData,
            async: false,
            cache: false,
            processData: false,
            contentType: false,
            url: form.attr('action'),
            type: form.attr('method'),
            error: function(xhr, status, error) {
                if (status==="timeout") {
                    alert(msg_timeout);
                } else {
                    alert(msg_error);
                }
            },
            success: function(response) {
                alert(response);
            },
            timeout: 7000
        });
    });
    

  4. 4.HTML

    HTML

     <input type="file" id="multiupload" name="uploadFiledd[]" multiple >
     <button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
     <div id="uploadsts"></div>
    

    자바 스크립트

        <script>
    
        function uploadajax(ttl,cl){
    
        var fileList = $('#multiupload').prop("files");
        $('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
    
        var form_data =  "";
    
        form_data = new FormData();
        form_data.append("upload_image", fileList[cl]);
    
    
        var request = $.ajax({
                  url: "upload.php",
                  cache: false,
                  contentType: false,
                  processData: false,
                  async: true,
                  data: form_data,
                  type: 'POST', 
                  xhr: function() {  
                      var xhr = $.ajaxSettings.xhr();
                      if(xhr.upload){ 
                      xhr.upload.addEventListener('progress', function(event){
                          var percent = 0;
                          if (event.lengthComputable) {
                              percent = Math.ceil(event.loaded / event.total * 100);
                          }
                          $('#prog'+cl).text(percent+'%') 
                       }, false);
                     }
                     return xhr;
                  },
                  success: function (res, status) {
                      if (status == 'success') {
                          percent = 0;
                          $('#prog' + cl).text('');
                          $('#prog' + cl).text('--Success: ');
                          if (cl < ttl) {
                              uploadajax(ttl, cl + 1);
                          } else {
                              alert('Done');
                          }
                      }
                  },
                  fail: function (res) {
                      alert('Failed');
                  }    
              })
        }
    
        $('#upcvr').click(function(){
            var fileList = $('#multiupload').prop("files");
            $('#uploadsts').html('');
            var i;
            for ( i = 0; i < fileList.length; i++) {
                $('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
                if(i == fileList.length-1){
                    uploadajax(fileList.length-1,0);
                }
             }
        });
        </script>
    

    PHP

    upload.php
        move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
    
  5. from https://stackoverflow.com/questions/19295746/how-to-upload-multiple-files-using-php-jquery-and-ajax by cc-by-sa and MIT license