[jquery] jQuery를 사용한 파일 업로드 진행률 표시 줄

내 프로젝트에서 AJAX 파일 업로드 기능을 구현하려고합니다. 이를 위해 jQuery를 사용하고 있습니다. 내 코드는 AJAX를 사용하여 데이터를 제출합니다. 또한 파일 업로드 진행률 표시 줄을 구현하고 싶습니다. 어떻게 할 수 있습니까? 업로드 된 비율을 계산하고 진행률 표시 줄을 만들 수 있도록 이미 얼마나 많이 업로드되었는지 계산하는 방법이 있습니까?



답변

참고 : 이 질문은 jQuery 양식 플러그인 과 관련이 있습니다 . 순수한 jQuery 솔루션을 찾고 있다면 여기 에서 시작하십시오 . 모든 브라우저에 대한 전반적인 jQuery 솔루션은 없습니다. 따라서 플러그인을 사용해야합니다. 이전 브라우저를 쉽게 대체 할 수있는 dropzone.js를 사용 하고 있습니다. 선호하는 플러그인은 필요에 따라 다릅니다. 거기에 좋은 비교 게시물이 많이 있습니다.

로부터 :

jQuery :

$(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
});

html :

<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>

css로 진행률 표시 줄 스타일을 지정해야합니다.


답변

jQuery로만이 작업을 수행했습니다.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
        console.log(percentComplete);

        if (percentComplete === 100) {

        }

      }
    }, false);

    return xhr;
  },
  url: posturlfile,
  type: "POST",
  data: JSON.stringify(fileuploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});


답변

내 프로젝트에서 다음을 사용했습니다. 당신도 시도 할 수 있습니다.

ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {

    if (ajax.status) {

        if (ajax.status == 200 && (ajax.readyState == 4)){
            //To do tasks if any, when upload is completed
        }
    }
}
ajax.upload.addEventListener("progress", function (event) {

    var percent = (event.loaded / event.total) * 100;
    //**percent** variable can be used for modifying the length of your progress bar.
    console.log(percent);

});

ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.


답변

이것을 확인하십시오 : http://hayageek.com/docs/jquery-upload-file.php
실수로 인터넷에서 발견했습니다.


답변

프로젝트에서 jquery를 사용 중이고 처음부터 업로드 메커니즘을 구현하지 않으려는 경우 https://github.com/blueimp/jQuery-File-Upload 를 사용할 수 있습니다 .

여러 파일 선택, 드래그 앤 드롭 지원, 진행률 표시 줄, 유효성 검사 및 미리보기 이미지, 교차 도메인 지원, 청크 및 재개 가능한 파일 업로드가 포함 된 매우 멋진 API가 있습니다. 또한 여러 서버 언어 (node, php, python 및 go)에 대한 샘플 스크립트가 있습니다.

데모 URL : https://blueimp.github.io/jQuery-File-Upload/ .


답변

다음은보다 완전한 jquery 1.11.x $ .ajax () 사용법입니다.

<script type="text/javascript">
    function uploadProgressHandler(event) {
        $("#loaded_n_total").html("Uploaded " + event.loaded + " bytes of " + event.total);
        var percent = (event.loaded / event.total) * 100;
        var progress = Math.round(percent);
        $("#uploadProgressBar").html(progress + " percent na ang progress");
        $("#uploadProgressBar").css("width", progress + "%");
        $("#status").html(progress + "% uploaded... please wait");
    }

    function loadHandler(event) {
        $("#status").html(event.target.responseText);
        $("#uploadProgressBar").css("width", "0%");
    }

    function errorHandler(event) {
        $("#status").html("Upload Failed");
    }

    function abortHandler(event) {
        $("#status").html("Upload Aborted");
    }

    $("#uploadFile").click(function (event) {
        event.preventDefault();
        var file = $("#fileUpload")[0].files[0];
        var formData = new FormData();
        formData.append("file1", file);

        $.ajax({
            url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
            method: 'POST',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            xhr: function () {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress",
                    uploadProgressHandler,
                    false
                );
                xhr.addEventListener("load", loadHandler, false);
                xhr.addEventListener("error", errorHandler, false);
                xhr.addEventListener("abort", abortHandler, false);

                return xhr;
            }
        });
    });
</script>


답변

이것은 내 문제를 해결했습니다.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i');
          $link.html('Uploading..('+percentComplete+'%)');
          $link.append($img);
      }
    }, false);

    return xhr;
  },
  url: posturlfile,
  type: "POST",
  data: JSON.stringify(fileuploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});