카테고리 없음

[자바 스크립트] 파일을 비동기 적으로 업로드하려면 어떻게해야합니까?

행복을전해요 2021. 2. 16. 09:51

HTML5사용하면 Ajax 및 jQuery를 사용하여 파일을 업로드 할 수 있습니다. 뿐만 아니라 파일 유효성 검사 (이름, 크기 및 MIME 유형)를 수행하거나 HTML5 진행률 태그 (또는 div)를 사용하여 진행률 이벤트를 처리 할 수 ​​있습니다. 최근에 파일 업 로더를 만들어야했지만 Flash 나 Iframe, 플러그인 을 사용하고 싶지 않았고 몇 가지 조사 끝에 해결책을 찾았습니다.

HTML :

<form enctype="multipart/form-data">
    <input name="file" type="file" />
        <input type="button" value="Upload" />
        </form>
        <progress></progress>
        

첫째, 원하는 경우 몇 가지 유효성 검사를 수행 할 수 있습니다. 예를 들어, .on('change')파일의 경우 :

$(':file').on('change', function () {
  var file = this.files[0];
  
    if (file.size > 1024) {
        alert('max upload size is 1k');
          }
          
            // Also see .name, .type
            });
            

이제 $.ajax()버튼을 클릭 하여 제출하십시오.

$(':button').on('click', function () {
  $.ajax({
      // Your server script to process the upload
          url: 'upload.php',
              type: 'POST',
              
                  // Form data
                      data: new FormData($('form')[0]),
                      
                          // Tell jQuery not to process data or worry about content-type
                              // You *must* include these options!
                                  cache: false,
                                      contentType: false,
                                          processData: false,
                                          
                                              // Custom XMLHttpRequest
                                                  xhr: function () {
                                                        var myXhr = $.ajaxSettings.xhr();
                                                              if (myXhr.upload) {
                                                                      // For handling the progress of the upload
                                                                              myXhr.upload.addEventListener('progress', function (e) {
                                                                                        if (e.lengthComputable) {
                                                                                                    $('progress').attr({
                                                                                                                  value: e.loaded,
                                                                                                                                max: e.total,
                                                                                                                                            });
                                                                                                                                                      }
                                                                                                                                                              }, false);
                                                                                                                                                                    }
                                                                                                                                                                          return myXhr;
                                                                                                                                                                              }
                                                                                                                                                                                });
                                                                                                                                                                                });
                                                                                                                                                                                

보시다시피 HTML5 (및 일부 연구)를 사용하면 파일 업로드가 가능할뿐만 아니라 매우 쉽습니다. 예제의 HTML5 구성 요소 중 일부는 모든 브라우저에서 사용할 수있는 것은 아니므로 Chrome에서 사용 해보세요 .

-------------------

2019 업데이트 : 그것은 여전히 브라우저에 따라 당신의 인구 통계 학적 사용합니다.

"새로운"HTML5 fileAPI 로 이해해야 할 중요한 점 IE 10까지 지원되지 않았다는 것 입니다. 목표로 삼고있는 특정 시장에서 이전 버전의 Windows에 대한 성향이 평균보다 높으면 해당 시장에 액세스하지 못할 수 있습니다.

2017 년 현재 브라우저의 약 5 %가 IE 6, 7, 8 또는 9 중 하나입니다. 대기업 (예 : B2B 도구 또는 교육용으로 제공하는 도구)으로 이동하면 그 수가 급증 할 수 있습니다. . 2016 년에 저는 60 %가 넘는 컴퓨터에서 IE8을 사용하는 회사와 거래했습니다.

제가 처음 답변 한 지 거의 11 년이 지난 지금은 2019 년입니다. IE9 이하는 전 세계적으로 약 1 % 정도이지만 여전히 사용량이 많은 클러스터가 있습니다.

피쳐가 -whatever이에서 중요한 멀리 걸릴, 어떤 브라우저를 확인 하여 사용자가 사용 . 그렇지 않은 경우 "나를 위해 작동"이 고객에게 제공 할 수있는 서비스가 충분하지 않은 이유에 대한 빠르고 고통스러운 교훈을 얻을 수 있습니다. caniuse 는 유용한 도구이지만 인구 통계를 어디에서 가져 오는지 기록해 둡니다 . 그들은 당신의 것과 일치하지 않을 수 있습니다. 이것은 엔터프라이즈 환경보다 결코 사실이 아닙니다.

2008 년의 대답은 다음과 같습니다.


그러나 파일 업로드의 실행 가능한 비 JS 방법이 있습니다. 페이지에 iframe (CSS로 숨긴)을 만든 다음 양식을 대상으로 해당 iframe에 게시 할 수 있습니다. 메인 페이지는 이동할 필요가 없습니다.

"진짜"게시물이므로 완전히 상호 작용하지 않습니다. 상태가 필요한 경우 처리하기 위해 서버 측이 필요합니다. 이것은 서버에 따라 크게 다릅니다. ASP.NET 에는 더 좋은 메커니즘이 있습니다. PHP 일반은 실패하지만 Perl 또는 Apache 수정을 사용하여 해결할 수 있습니다 .

여러 파일 업로드가 필요한 경우 각 파일을 한 번에 하나씩 수행하는 것이 가장 좋습니다 (최대 파일 업로드 제한을 극복하기 위해). 첫 번째 양식을 iframe에 게시하고, 위를 사용하여 진행 상황을 모니터링하고, 완료되면 두 번째 양식을 iframe에 게시하는 등의 작업을 수행합니다.

또는 Java / Flash 솔루션을 사용하십시오. 게시물로 할 수있는 작업이 훨씬 더 유연합니다.

-------------------

이 목적으로 Fine Uploader 플러그인을 사용하는 것이 좋습니다 . 귀하의 JavaScript코드는 다음과 같습니다

$(document).ready(function() {
  $("#uploadbutton").jsupload({
      action: "addFile.do",
          onComplete: function(response){
                alert( "server response: " + response);
                    }
                      });
                      });
                      
-------------------

참고 :이 답변은 오래되었습니다. 이제 XHR을 사용하여 파일을 업로드 할 수 있습니다.


XMLHttpRequest (Ajax)를 사용하여 파일을 업로드 할 수 없습니다 . iframe 또는 Flash를 사용하여 효과를 시뮬레이션 할 수 있습니다. 효과를 얻기 위해 iframe을 통해 파일을 게시 하는 우수한 jQuery Form Plugin .

-------------------

미래 독자를 위해 마무리합니다.

비동기 파일 업로드

HTML5 사용

FormDataFile API 가 지원되는 경우 (HTML5 기능 모두) 메소드를 사용하여 jQuery로 파일 업로드 할 수 있습니다 .$.ajax()

FormData없이 파일 보낼 수도 있지만 XMLHttpRequest (Ajax) 로 보낼 수있는 방식으로 파일을 처리하려면 File API가 있어야합니다 .

$.ajax({
  url: 'file/destination.html', 
    type: 'POST',
      data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
        processData: false,
          contentType: false                    // Using FormData, no need to process data.
          }).done(function(){
            console.log("Success: Files sent!");
            }).fail(function(){
              console.log("An error occurred, the files couldn't be sent!");
              });
              

빠르고 순수한 JavaScript ( jQuery 없음 ) 예제는 " FormData 객체를 사용하여 파일 보내기 "를 참조하십시오 .

폴백

HTML5가 지원되지 않는 경우 ( 파일 API 없음 ) 유일한 다른 순수 자바 스크립트 솔루션 ( 플래시 또는 기타 브라우저 플러그인 없음)은 숨겨진 iframe 기술로, XMLHttpRequest 객체 를 사용하지 않고 비동기 요청을 에뮬레이트 할 수 있습니다 .

파일 입력을 사용하여 iframe을 양식의 대상으로 설정하는 것으로 구성됩니다. 사용자가 요청을 제출하면 파일이 업로드되지만 메인 페이지를 다시 렌더링하는 대신 iframe 내에 응답이 표시됩니다. iframe을 숨기면 전체 프로세스가 사용자에게 투명 해지고 비동기식 요청이 에뮬레이트됩니다.

제대로 수행되면 거의 모든 브라우저에서 작동하지만 iframe에서 응답을 얻는 방법에 대한 몇 가지주의 사항이 있습니다.

이 경우 같은 래퍼 플러그인을 사용하는 것이 좋습니다 비프로스트 용도 iframe이 기술을 뿐만 아니라 제공 jQuery를 아약스 수송 할 수 있도록 파일을 보낼 단지와 $.ajax()같은 방법 :

$.ajax({
  url: 'file/destination.html', 
    type: 'POST',
      // Set the transport to use (iframe means to use Bifröst)
        // and the expected data type (json in this case).
          dataType: 'iframe json',                                
            fileInputs: $('input[type="file"]'),  // The file inputs containing the files to send.
              data: { msg: 'Some extra data you might need.'}
              }).done(function(){
                console.log("Success: Files sent!");
                }).fail(function(){
                  console.log("An error occurred, the files couldn't be sent!");
                  });
                  

플러그인

Bifröst 는 jQuery의 ajax 메서드에 폴백 지원을 추가하는 작은 래퍼 일 뿐이지 만 jQuery Form Plugin 또는 jQuery File Upload 와 같은 앞서 언급 한 많은 플러그인 에는 HTML5에서 다른 폴백으로의 전체 스택과 프로세스를 용이하게하는 몇 가지 유용한 기능이 포함되어 있습니다. 필요와 요구 사항에 따라 베어 구현 또는이 플러그인 중 하나를 고려할 수 있습니다.

-------------------

AJAX 파일 업로드 jQuery 플러그인 은 파일을 업로드하고 응답을 콜백에 전달합니다.

  • 특정 HTML에 의존하지 않고 <input type="file">
  • 서버가 특정 방식으로 응답 할 필요가 없습니다.
  • 사용하는 파일의 수나 페이지의 위치는 중요하지 않습니다.

-최소 사용-

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
  });
  

-또는만큼-

$('input[type="file"]').ajaxfileupload({
  'action': '/upload.php',
    'params': {
        'extra': 'info'
          },
            'onComplete': function(response) {
                console.log('custom handler for file:');
                    alert(JSON.stringify(response));
                      },
                        'onStart': function() {
                            if(weWantedTo) return false; // cancels upload
                              },
                                'onCancel': function() {
                                    console.log('no file selected');
                                      }
                                      });
                                      
-------------------

아래 스크립트를 사용하여 잘 작동하는 이미지를 업로드했습니다.

HTML

<input id="file" type="file" name="file"/>
<div id="response"></div>

자바 스크립트

jQuery('document').ready(function(){
    var input = document.getElementById("file");
        var formdata = false;
            if (window.FormData) {
                    formdata = new FormData();
                        }
                            input.addEventListener("change", function (evt) {
                                    var i = 0, len = this.files.length, img, reader, file;
                                    
                                            for ( ; i < len; i++ ) {
                                                        file = this.files[i];
                                                        
                                                                    if (!!file.type.match(/image.*/)) {
                                                                                    if ( window.FileReader ) {
                                                                                                        reader = new FileReader();
                                                                                                                            reader.onloadend = function (e) {
                                                                                                                                                    //showUploadedItem(e.target.result, file.fileName);
                                                                                                                                                                        };
                                                                                                                                                                                            reader.readAsDataURL(file);
                                                                                                                                                                                                            }
                                                                                                                                                                                                            
                                                                                                                                                                                                                            if (formdata) {
                                                                                                                                                                                                                                                formdata.append("image", file);
                                                                                                                                                                                                                                                                    formdata.append("extra",'extra-data');
                                                                                                                                                                                                                                                                                    }
                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                    if (formdata) {
                                                                                                                                                                                                                                                                                                                        jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
                                                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                                                            jQuery.ajax({
                                                                                                                                                                                                                                                                                                                                                                    url: "upload.php",
                                                                                                                                                                                                                                                                                                                                                                                            type: "POST",
                                                                                                                                                                                                                                                                                                                                                                                                                    data: formdata,
                                                                                                                                                                                                                                                                                                                                                                                                                                            processData: false,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    contentType: false,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            success: function (res) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     jQuery('div#response').html("Successfully uploaded");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         else
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     alert('Not a vaild image!');
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             }, false);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

설명

나는 div업로드가 완료된 후 업로드 애니메이션과 응답 을 보여주기 위해 응답 사용 합니다.

가장 좋은 부분은이 스크립트를 사용할 때 파일과 함께 ID 등의 추가 데이터를 보낼 수 있다는 것입니다. extra-data대본에서와 같이 언급했습니다 .

PHP 수준에서는 일반적인 파일 업로드로 작동합니다. 추가 데이터는 데이터로 검색 할 수 있습니다 $_POST.

여기서는 플러그인 등을 사용하지 않습니다. 원하는대로 코드를 변경할 수 있습니다. 여기서 맹목적으로 코딩하는 것이 아닙니다. 이것은 모든 jQuery 파일 업로드의 핵심 기능입니다. 사실 자바 스크립트.

-------------------

바닐라 자바 ​​스크립트로 아주 쉽게 할 수 있습니다. 내 현재 프로젝트의 스 니펫은 다음과 같습니다.

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
        // Render a pretty progress bar
        };
        xhr.onreadystatechange = function(e) {
            if(this.readyState === 4) {
                    // Handle file upload complete
                        }
                        };
                        xhr.open('POST', '/upload', true);
                        xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
                        xhr.send(file);
                        
-------------------

jQuery로 간단히 업로드 할 수 있습니다 .ajax().

HTML :

<form id="upload-form">
    <div>
            <label for="file">File:</label>
                    <input type="file" id="file" name="file" />
                            <progress class="progress" value="0" max="100"></progress>
                                </div>
                                    <hr />
                                        <input type="submit" value="Submit" />
                                        </form>
                                        

CSS

.progress { display: none; }

자바 스크립트 :

$(document).ready(function(ev) {
    $("#upload-form").on('submit', (function(ev) {
            ev.preventDefault();
                    $.ajax({
                                xhr: function() {
                                                var progress = $('.progress'),
                                                                    xhr = $.ajaxSettings.xhr();
                                                                    
                                                                                    progress.show();
                                                                                    
                                                                                                    xhr.upload.onprogress = function(ev) {
                                                                                                                        if (ev.lengthComputable) {
                                                                                                                                                var percentComplete = parseInt((ev.loaded / ev.total) * 100);
                                                                                                                                                                        progress.val(percentComplete);
                                                                                                                                                                                                if (percentComplete === 100) {
                                                                                                                                                                                                                            progress.hide().val(0);
                                                                                                                                                                                                                                                    }
                                                                                                                                                                                                                                                                        }
                                                                                                                                                                                                                                                                                        };
                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                        return xhr;
                                                                                                                                                                                                                                                                                                                    },
                                                                                                                                                                                                                                                                                                                                url: 'upload.php',
                                                                                                                                                                                                                                                                                                                                            type: 'POST',
                                                                                                                                                                                                                                                                                                                                                        data: new FormData(this),
                                                                                                                                                                                                                                                                                                                                                                    contentType: false,
                                                                                                                                                                                                                                                                                                                                                                                cache: false,
                                                                                                                                                                                                                                                                                                                                                                                            processData: false,
                                                                                                                                                                                                                                                                                                                                                                                                        success: function(data, status, xhr) {
                                                                                                                                                                                                                                                                                                                                                                                                                        // ...
                                                                                                                                                                                                                                                                                                                                                                                                                                    },
                                                                                                                                                                                                                                                                                                                                                                                                                                                error: function(xhr, status, error) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                // ...
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       }));
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
-------------------

이전에이 작업을 수행 한 가장 간단하고 강력한 방법은 양식으로 숨겨진 iFrame 태그를 대상으로 지정하는 것입니다. 그러면 페이지를 다시로드하지 않고 iframe 내에서 제출됩니다.

플러그인, JavaScript 또는 HTML 이외의 다른 형태의 "마법"을 사용하고 싶지 않은 경우입니다. 물론 이것을 자바 스크립트와 결합 할 수 있습니다.

<form target="iframe" action="" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
        <input type="button" value="Upload" />
        </form>
        
        <iframe name="iframe" id="iframe" style="display:none" ></iframe>
        

onLoad서버 오류 또는 성공 응답 에 대한 iframe의 내용을 읽고 사용자에게 출력 할 수도 있습니다.

Chrome, iFrame 및 onLoad

-참고-업로드 / 다운로드를 할 때 UI 차단기를 설정하는 방법에 관심이있는 경우에만 계속 읽으면됩니다.

현재 Chrome은 파일 전송에 사용될 때 iframe에 대한 onLoad 이벤트를 트리거하지 않습니다. Firefox, IE 및 Edge는 모두 파일 전송을 위해 onload 이벤트를 발생시킵니다.

Chrome에서 작동하는 유일한 해결책은 쿠키를 사용하는 것입니다.

기본적으로 업로드 / 다운로드가 시작될 때이를 수행하려면 :

  • [클라이언트 측] 쿠키의 존재를 찾기위한 간격 시작
  • [서버 측] 파일 데이터로 필요한 모든 작업 수행
  • [서버 측] 클라이언트 측 간격에 대한 쿠키 설정
  • [Client Side] Interval은 쿠키를보고 onLoad 이벤트처럼 사용합니다. 예를 들어 UI 차단기를 시작한 다음 onLoad (또는 쿠키가 만들어 질 때) UI 차단기를 제거 할 수 있습니다.

이를 위해 쿠키를 사용하는 것은 추악하지만 작동합니다.

다운로드 할 때 Chrome에서이 문제를 처리하기 위해 jQuery 플러그인을 만들었습니다. 여기에서 찾을 수 있습니다.

https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js

동일한 기본 원칙이 업로드에도 적용됩니다.

다운로더를 사용하려면 (당연히 JS 포함)

 $('body').iDownloader({
     "onComplete" : function(){
               $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
                    }
                     });
                     
                      $('somebuttion').click( function(){
                            $('#uiBlocker').css('display', 'block'); //block the UI
                                  $('body').iDownloader('download', 'htttp://example.com/location/of/download');
                                   });
                                   

그리고 서버 측에서 파일 데이터를 전송하기 직전에 쿠키를 만듭니다.

 setcookie('iDownloader', true, time() + 30, "/");

플러그인은 쿠키를보고 onComplete콜백 을 트리거합니다 .

-------------------

내가 찾은 해결책은 <form>대상에 숨겨진 iFrame 을 갖는 것 입니다. 그런 다음 iFrame은 JS를 실행하여 사용자에게 완료되었음을 표시합니다 (페이지로드시).

-------------------

저는 이것을 Rails 환경에서 작성했습니다 . 가벼운 jQuery-form 플러그인을 사용하는 경우 약 5 줄의 자바 스크립트입니다.

문제는 표준 remote_form_for이 다중 파트 양식 제출을 이해하지 못하기 때문에 AJAX 업로드가 작동하도록하는 것입니다. Rails가 AJAX 요청으로 검색하는 파일 데이터를 보내지 않습니다.

그것이 jQuery-form 플러그인이 작동하는 곳입니다.

이에 대한 Rails 코드는 다음과 같습니다.

<% remote_form_for(:image_form, 
                   :url => { :controller => "blogs", :action => :create_asset }, 
                                      :html => { :method => :post, 
                                                                    :id => 'uploadForm', :multipart => true }) 
                                                                                                                                            do |f| %>
                                                                                                                                             Upload a file: <%= f.file_field :uploaded_data %>
                                                                                                                                             <% end %>
                                                                                                                                             

관련 JavaScript는 다음과 같습니다.

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
   beforeSubmit: function(a,f,o) {
      o.dataType = 'json';
        },
          complete: function(XMLHttpRequest, textStatus) {
             // XMLHttpRequest.responseText will contain the URL of the uploaded image.
                // Put it in an image element you create, or do with it what you will.
                   // For example, if you have an image elemtn with id "my_image", then
                      //  $('#my_image').attr('src', XMLHttpRequest.responseText);
                         // Will set that image tag to display the uploaded image.
                           },
                            });
                            });
                            

그리고 여기 Rails 컨트롤러 액션이 있습니다.

 @image = Image.new(params[:image_form])
 @image.save
  render :text => @image.public_filename
  

저는 Bloggity에서 지난 몇 주 동안 이것을 사용해 왔으며 챔피언처럼 작동했습니다.

-------------------

Simple Ajax Uploader는 또 다른 옵션입니다.

https://github.com/LPology/Simple-Ajax-Uploader

  • 크로스 브라우저-IE7 +, Firefox, Chrome, Safari, Opera에서 작동합니다.
  • 비 HTML5 브라우저에서도 여러 동시 업로드 지원
  • 플래시 또는 외부 CSS 없음-단 하나의 5Kb 자바 스크립트 파일
  • 완전한 크로스 브라우저 진행률 표시 줄에 대한 옵션 내장 지원 (PHP의 APC 확장 사용)
  • 유연하고 고도로 사용자 정의 가능-모든 요소를 ​​업로드 버튼으로 사용하고 자신 만의 진행률 표시기 스타일을 지정합니다.
  • 양식이 필요하지 않으며 업로드 버튼으로 사용할 요소 만 제공하세요.
  • MIT 라이선스-상용 프로젝트에서 무료로 사용 가능

사용 예 :

var uploader = new ss.SimpleUpload({
    button: $('#uploadBtn'), // upload button
        url: '/uploadhandler', // URL of server-side upload handler
            name: 'userfile', // parameter name of the uploaded file
                onSubmit: function() {
                        this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
                            },
                                onComplete: function(file, response) {
                                        // do whatever after upload is finished
                                            }
                                            });
                                            
-------------------

jQuery Uploadify 는 이전에 파일을 업로드하는 데 사용한 또 다른 좋은 플러그인입니다. JavaScript 코드는 다음과 같이 간단합니다. 코드. 그러나 새 버전은 Internet Explorer에서 작동하지 않습니다.

$('#file_upload').uploadify({
    'swf': '/public/js/uploadify.swf',
        'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
            'cancelImg': '/public/images/uploadify-cancel.png',
                'multi': true,
                    'onQueueComplete': function (queueData) {
                            // ...
                                },
                                    'onUploadStart': function (file) {
                                            // ...
                                                }
                                                });
                                                

나는 많은 검색을 해왔고 플러그인없이 ajax로만 파일을 업로드하는 또 다른 솔루션을 찾았습니다. 해결책은 다음과 같습니다.

$(document).ready(function () {
    $('#btn_Upload').live('click', AjaxFileUpload);
    });
    
    function AjaxFileUpload() {
        var fileInput = document.getElementById("#Uploader");
            var file = fileInput.files[0];
                var fd = new FormData();
                    fd.append("files", file);
                        var xhr = new XMLHttpRequest();
                            xhr.open("POST", 'Uploader.ashx');
                                xhr.onreadystatechange = function () {
                                        if (xhr.readyState == 4) {
                                                     alert('success');
                                                             }
                                                                     else if (uploadResult == 'success')
                                                                                 alert('error');
                                                                                     };
                                                                                         xhr.send(fd);
                                                                                         }
                                                                                         
-------------------

여기에 (파일을 업로드하는 방법의 또 다른 해결책 어떤 플러그인을 사용하지 않고는 )

간단한 자바 스크립트AJAX 사용 (진행률 표시 줄 포함)

HTML 부분

<form id="upload_form" enctype="multipart/form-data" method="post">
    <input type="file" name="file1" id="file1"><br>
        <input type="button" value="Upload File" onclick="uploadFile()">
            <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
                <h3 id="status"></h3>
                    <p id="loaded_n_total"></p>
                    </form>
                    

JS 부분

function _(el){
    return document.getElementById(el);
    }
    function uploadFile(){
        var file = _("file1").files[0];
            // alert(file.name+" | "+file.size+" | "+file.type);
                var formdata = new FormData();
                    formdata.append("file1", file);
                        var ajax = new XMLHttpRequest();
                            ajax.upload.addEventListener("progress", progressHandler, false);
                                ajax.addEventListener("load", completeHandler, false);
                                    ajax.addEventListener("error", errorHandler, false);
                                        ajax.addEventListener("abort", abortHandler, false);
                                            ajax.open("POST", "file_upload_parser.php");
                                                ajax.send(formdata);
                                                }
                                                function progressHandler(event){
                                                    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
                                                        var percent = (event.loaded / event.total) * 100;
                                                            _("progressBar").value = Math.round(percent);
                                                                _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
                                                                }
                                                                function completeHandler(event){
                                                                    _("status").innerHTML = event.target.responseText;
                                                                        _("progressBar").value = 0;
                                                                        }
                                                                        function errorHandler(event){
                                                                            _("status").innerHTML = "Upload Failed";
                                                                            }
                                                                            function abortHandler(event){
                                                                                _("status").innerHTML = "Upload Aborted";
                                                                                }
                                                                                

PHP 부분

<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
        }
        if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
            echo "$fileName upload is complete";
            } else {
                echo "mo