복붙노트

[JQUERY] 어떻게 비동기 적으로 파일을 업로드 할 수 있습니까?

JQUERY

어떻게 비동기 적으로 파일을 업로드 할 수 있습니까?

해결법


  1. 1.HTML5를 사용하면 Ajax와 jQuery로 파일 업로드를 할 수 있습니다. 뿐만 아니라, 당신이 파일 검증 (이름, 크기, MIME 타입)을 수행하거나 HTML5 진행 태그 (또는 사업부)로 진행 이벤트를 처리 할 수 ​​있습니다. 최근에 나는 파일 업 로더를했습니다,하지만 난 플래시도 Iframe이 나 플러그인을 사용하지 않았고, 몇 가지 조사 후 나는 해결책을했다.

    HTML5를 사용하면 Ajax와 jQuery로 파일 업로드를 할 수 있습니다. 뿐만 아니라, 당신이 파일 검증 (이름, 크기, MIME 타입)을 수행하거나 HTML5 진행 태그 (또는 사업부)로 진행 이벤트를 처리 할 수 ​​있습니다. 최근에 나는 파일 업 로더를했습니다,하지만 난 플래시도 Iframe이 나 플러그인을 사용하지 않았고, 몇 가지 조사 후 나는 해결책을했다.

    html로 :

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

    당신이 원하는 경우 먼저, 당신은 몇 가지 유효성 검사를 할 수 있습니다. 예를 들어, 파일의 이벤트 CSTE 연구진 ( '변화')에서 :

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

    지금은 $ 아약스 () 버튼의 클릭으로 제출

    $(':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 구성 요소 중 일부는 모든 브라우저에서 사용할 수 없습니다 구글 크롬 그것을 시도하십시오.


  2. 2."새로운"HTML5 파일 API를 이해하는 중요한 것은 당신이 목표로하고있는 특정 시장이 이전 버전의 Windows 향해보다 높은 평균 성향이있는 경우는 IE (10)까지 지원되지 않았 음을, 당신은 그렇지 않을 수 있습니다 그것은에 액세스 할 수 있습니다.

    "새로운"HTML5 파일 API를 이해하는 중요한 것은 당신이 목표로하고있는 특정 시장이 이전 버전의 Windows 향해보다 높은 평균 성향이있는 경우는 IE (10)까지 지원되지 않았 음을, 당신은 그렇지 않을 수 있습니다 그것은에 액세스 할 수 있습니다.

    당신은 큰 기업으로 향할 경우 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는 일반 실패,하지만 당신은 그것을 해결하기 위해 펄이나 아파치의 수정을 사용할 수 있습니다.

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

    아니면 자바 / 플래시 솔루션을 사용합니다. 그들은 자신의 게시물과 함께 무엇을 할 수 있는지에 훨씬 더 유연한있어 ...


  3. 3.나는이 목적을 위해 미세 업 로더 플러그인을 사용하는 것이 좋습니다. 자바 스크립트 코드는 다음과 같습니다

    나는이 목적을 위해 미세 업 로더 플러그인을 사용하는 것이 좋습니다. 자바 스크립트 코드는 다음과 같습니다

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

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

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

    당신은 XMLHttpRequest의 (아약스)을 사용하여 파일을 업로드 할 수 없습니다. 당신은 iframe이 또는 Flash를 사용하여 효과를 시뮬레이션 할 수 있습니다. 우수한 jQuery를 양식 플러그인은 iframe을 통해 게시물 파일은 효과를 얻을 수있다.


  5. 5.미래의 독자를 위해 포장.

    미래의 독자를 위해 포장.

    당신은 FormData하고 파일 API가 (모두 HTML5 기능)를 지원하는 경우 jQuery를가 $의 아약스 () 메소드를 사용하여 파일을 업로드 할 수 있습니다.

    또한 FormData하지만, 파일 API 그들이 XMLHttpRequest의 (아약스)로 전송 될 수 있도록 프로세스 파일에 있어야합니다 어느 쪽이든없이 파일을 보낼 수 있습니다.

    $.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!");
    });
    

    빠른 들어, 순수 자바 스크립트 (NO jQuery를) 예를 들어 페이지의 "FormData 객체를 사용하여 파일을 전송".

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

    이 파일 입력을 가진 형태의 대상으로 설정 iframe이 구성된다. 요청이 만들어 사용자 제출하고, 파일이 업로드되지만 응답은 iframe을 대신의 메인 페이지를 다시 렌더링 안에 표시됩니다. iframe을 숨기기 사용자에게 전체 프로세스를 투명하게 비동기 요청을 에뮬레이트합니다.

    제대로하는 경우는 모든 브라우저에서 실질적으로 작동해야하지만 iframe이의 응답을 구하는 방법과 같은 몇 가지주의 사항이있다.

    이 경우 iframe이 기술을 사용 비프로스트 같은 래퍼 플러그인을 사용하는 것을 선호하지만,이 같은 단지 $ 아약스 () 메소드로 파일을 보낼 수 있도록 jQuery를 아약스의 전송을 제공 할 수 있습니다 :

    $.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!");
    });
    

    비프로스트는 jQuery의 아약스 방법으로 대체 지원을 추가하는 작은 래퍼이지만, jQuery를 양식 플러그인 또는 jQuery를 파일 업로드와 같은 전술 플러그인의 대부분은 HTML5와 다른 폴백 (fallback) 프로세스를 쉽게하기 위해 몇 가지 유용한 기능에 대한 전체 스택을 포함한다. 귀하의 필요와 요구 사항에 따라이 플러그인의 베어 구현 또는 중 하나를 고려할 수 있습니다.


  6. 6.이 AJAX 파일 업로드 jQuery를 플러그인 업로드 파일 어딘가에, 그리고 전달 콜백에 대한 응답, 아무것도.

    이 AJAX 파일 업로드 jQuery를 플러그인 업로드 파일 어딘가에, 그리고 전달 콜백에 대한 응답, 아무것도.

    - 사용 작은만큼 -

    $('#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');
      }
    });
    

  7. 7.나는 잘 작동으로 발생하는 이미지를 업로드하기 위해 아래의 스크립트를 사용하고있다.

    나는 잘 작동으로 발생하는 이미지를 업로드하기 위해 아래의 스크립트를 사용하고있다.

    <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를 사용합니다.

    가장 좋은 부분은이 스크립트를 사용할 때와 같은 파일과 IDS & 등으로 추가 데이터를 보낼 수있다. 나는 스크립트와 같은 추가 데이터를 언급합니다.

    PHP는 수준이 정상 파일 업로드로 작동합니다. 추가 데이터는 $ _POST 데이터로 검색 할 수 있습니다.

    여기 플러그인과 물건을 사용하고 있지 않습니다. 당신이 원하는대로 당신은 코드를 변경할 수 있습니다. 당신은 맹목적으로 여기에 코딩되어 있지 않습니다. 이것은 어떤 jQuery를 파일 업로드의 핵심 기능이다. 사실 자바 스크립트.


  8. 8.당신은 아주 쉽게 바닐라 자바 ​​스크립트에 그것을 할 수 있습니다. 여기에 내 현재 프로젝트에서 코드 조각입니다 :

    당신은 아주 쉽게 바닐라 자바 ​​스크립트에 그것을 할 수 있습니다. 여기에 내 현재 프로젝트에서 코드 조각입니다 :

    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);
    

  9. 9.당신의 jQuery 아약스로 간단하게 업로드 할 수 있습니다 ().

    당신의 jQuery 아약스로 간단하게 업로드 할 수 있습니다 ().

    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) {
                    // ...
                }
           });
        }));
    });
    

  10. 10.내가 과거에 이런 짓을했는지 가장 간단하고 강력한 방법은, 단순히 양식의 숨겨진 iframe 태그를 대상으로하는 것입니다 - 다음 페이지를 다시로드하지 않고 iframe 내에 제출합니다.

    내가 과거에 이런 짓을했는지 가장 간단하고 강력한 방법은, 단순히 양식의 숨겨진 iframe 태그를 대상으로하는 것입니다 - 다음 페이지를 다시로드하지 않고 iframe 내에 제출합니다.

    당신이 플러그인, 자바 스크립트 나 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>
    

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

    크롬 Iframe을, 그리고에 onLoad

    당신은 단지 당신이 설정하는 방법 UI 차단제에 업로드 / 다운로드를 할 때에 관심이 있다면 읽어 계속해야 -note-

    이 전송 파일에 사용되는 경우 현재 크롬은 iframe 대응의 onLoad 이벤트를 트리거하지 않습니다. 파이어 폭스, IE, 그리고 에지 모든 화재 파일 전송 onload 이벤트.

    내가 크롬에 대한 작품을 발견 한 유일한 해결책은 쿠키를 사용하는 것이 었습니다.

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

    이를 위해 쿠키를 사용하는 것은 추악한 그러나 그것은 작동합니다.

    내가 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 콜백을 트리거합니다.


  11. 11.내가 찾은 해결책은 숨겨진 iframe이 대상의 <양식> 것이 었습니다. iframe이는 그 때 (페이지로드) 전체의하는 사용자에게 표시 할 JS를 실행할 수 있습니다.

    내가 찾은 해결책은 숨겨진 iframe이 대상의 <양식> 것이 었습니다. iframe이는 그 때 (페이지로드) 전체의하는 사용자에게 표시 할 JS를 실행할 수 있습니다.


  12. 12.나는 레일 환경에서이 최대를 기록했습니다. 당신은 가벼운 jQuery를 양식 플러그인을 사용하는 경우는, 자바 스크립트의 단지 약 5 라인입니다.

    나는 레일 환경에서이 최대를 기록했습니다. 당신은 가벼운 jQuery를 양식 플러그인을 사용하는 경우는, 자바 스크립트의 단지 약 5 라인입니다.

    문제는 여러 부분으로 양식 제출을 이해하지 못하는 표준 remote_form_for로 일하고 AJAX 업로드를 받고입니다. 다시 AJAX 요청과 노력 레일 파일 데이터를 보내려고하고 있지 않다.

    JQuery와 양식 플러그인이 활동하기 시작하는 곳이다.

    여기에 대한 레일 코드는 다음과 같습니다

    <% 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 %>
    

    여기에 관련된 자바 스크립트는 다음과 같습니다

    $('#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.
      },
     });
    });
    

    그리고 여기에 레일 컨트롤러 액션, 꽤 바닐라이다 :

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

    나는 Bloggity와 지난 몇 주 동안이를 사용하고, 그것은 챔피언처럼 일입니다.


  13. 13.간단한 아약스 업 로더는 또 다른 옵션이다 :

    간단한 아약스 업 로더는 또 다른 옵션이다 :

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

    사용 예제 :

    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
        }
    });
    

  14. 14.jQuery를 Uploadify 내가 파일을 업로드하기 전에 사용했던 또 다른 좋은 플러그인입니다. 코드 : 자바 스크립트 코드는 다음과 같이 간단하다. 그러나 새 버전은 Internet Explorer에서 작동하지 않습니다.

    jQuery를 Uploadify 내가 파일을 업로드하기 전에 사용했던 또 다른 좋은 플러그인입니다. 코드 : 자바 스크립트 코드는 다음과 같이 간단하다. 그러나 새 버전은 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) {
            // ...
        }
    });
    

    나는 검색의 많은 일을하고 난 어떤 플러그인없이 오직 아약스와 업로드 파일에 대한 또 다른 솔루션에왔다. 이 솔루션은 다음과 같다 :

    $(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);
    }
    

  15. 15.여기에 (어떤 플러그인없이) 파일을 업로드하는 방법의 또 다른 솔루션입니다

    여기에 (어떤 플러그인없이) 파일을 업로드하는 방법의 또 다른 솔루션입니다

    사용하여 간단한 자바 스크립트와 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 "move_uploaded_file function failed";
    }
    ?>
    

    다음은 예제 응용 프로그램입니다


  16. 16.

    var formData=new FormData();
    formData.append("fieldname","value");
    formData.append("image",$('[name="filename"]')[0].files[0]);
    
    $.ajax({
        url:"page.php",
        data:formData,
        type: 'POST',
        dataType:"JSON",
        cache: false,
        contentType: false,
        processData: false,
        success:function(data){ }
    });
    

    당신은 이미지를 포함한 모든 값을 게시 할 양식 데이터를 사용할 수 있습니다.


  17. 17.비동기 단계 아래 jQuery를 사용하여 파일을 업로드하려면 :

    비동기 단계 아래 jQuery를 사용하여 파일을 업로드하려면 :

    프로젝트 공개 Nuget 관리자와 추가 패키지에서 1 단계 (가 와서 설치됩니다 JQuery와 파일 업로드는 (만 검색 상자에 작성해야합니다.)) URL : https://github.com/blueimp/jQuery-File-Upload

    이미 패키지 위에 실행하여 프로젝트에 추가 된 HTML 파일의 스크립트 아래 2 추가 단계 :

    코드 아래에 따라 3 단계 쓰기 파일 업로드 컨트롤 :

    <input id="upload" name="upload" type="file" />
    

    아래와 같이 기록을 UploadFile 같은 4 A를 JS 방법 단계 :

     function uploadFile(element) {
        
                $(element).fileupload({
        
                    dataType: 'json',
                    url: '../DocumentUpload/upload',
                    autoUpload: true,
                    add: function (e, data) {           
                      // write code for implementing, while selecting a file. 
                      // data represents the file data. 
                      //below code triggers the action in mvc controller
                      data.formData =
                                        {
                                         files: data.files[0]
                                        };
                      data.submit();
                    },
                    done: function (e, data) {          
                       // after file uploaded
                    },
                    progress: function (e, data) {
                        
                       // progress
                    },
                    fail: function (e, data) {
                        
                       //fail operation
                    },
                    stop: function () {
                        
                      code for cancel operation
                    }
                });
            
            };
    

    준비 함수 호출 요소 파일 업로드에서 5 단계는 다음에 따라 프로세스를 시작합니다 :

    $(document).ready(function()
    {
        uploadFile($('#upload'));
    
    });
    

    아래 당 6 쓰기 MVC 컨트롤러와 동작 단계 :

    public class DocumentUploadController : Controller
        {       
            
            [System.Web.Mvc.HttpPost]
            public JsonResult upload(ICollection<HttpPostedFileBase> files)
            {
                bool result = false;
    
                if (files != null || files.Count > 0)
                {
                    try
                    {
                        foreach (HttpPostedFileBase file in files)
                        {
                            if (file.ContentLength == 0)
                                throw new Exception("Zero length file!");                       
                            else 
                                //code for saving a file
    
                        }
                    }
                    catch (Exception)
                    {
                        result = false;
                    }
                }
    
    
                return new JsonResult()
                    {
                        Data=result
                    };
    
    
            }
    
        }
    

  18. 18.jQuery를하지 않고 현대적인 접근 방식은 사용자가 선택한 파일 다음 (들) 및 파일 목록이 FormData 객체를 감싸 게시 가져 오기 사용할 때 다시 <입력 유형 = "파일">에서 얻을 파일 목록 개체를 사용하는 것입니다.

    jQuery를하지 않고 현대적인 접근 방식은 사용자가 선택한 파일 다음 (들) 및 파일 목록이 FormData 객체를 감싸 게시 가져 오기 사용할 때 다시 <입력 유형 = "파일">에서 얻을 파일 목록 개체를 사용하는 것입니다.

    // The input DOM element // <input type="file">
    const inputElement = document.querySelector('input[type=file]');
    
    // Listen for a file submit from user
    inputElement.addEventListener('change', () => {
        const data = new FormData();
        data.append('file', inputElement.files[0]);
        data.append('imageName', 'flower');
    
        // You can then post it to your server.
        // Fetch can accept an object of type FormData on its  body
        fetch('/uploadImage', {
            method: 'POST',
            body: data
        });
    });
    

  19. 19.당신은 당신이 미리 서버에 폼 파일을 제출할 수있는 여기 데모 작업과 해결 솔루션을 볼 수 있습니다. 귀하의 경우를 들어, 서버에 파일 업로드를 촉진하기 위해 Ajax를 사용해야합니다 :

    당신은 당신이 미리 서버에 폼 파일을 제출할 수있는 여기 데모 작업과 해결 솔루션을 볼 수 있습니다. 귀하의 경우를 들어, 서버에 파일 업로드를 촉진하기 위해 Ajax를 사용해야합니다 :

    <from action="" id="formContent" method="post" enctype="multipart/form-data">
        <span>File</span>
        <input type="file" id="file" name="file" size="10"/>
        <input id="uploadbutton" type="button" value="Upload"/>
    </form>
    

    제출 된 데이터는 formdata이다. 당신의 jQuery를에, 아래와 같이 양식 파일을 제출하는 대신 버튼 클릭의 기능을 제출 양식을 사용합니다.

    $(document).ready(function () {
       $("#formContent").submit(function(e){
    
         e.preventDefault();
         var formdata = new FormData(this);
    
     $.ajax({
         url: "ajax_upload_image.php",
         type: "POST",
         data: formdata,
         mimeTypes:"multipart/form-data",
         contentType: false,
         cache: false,
         processData: false,
         success: function(){
    
         alert("successfully submitted");
    
         });
       });
    });
    

    자세한 내용보기


  20. 20.샘플 : 당신이 jQuery를 사용하면 업로드 파일을 쉽게 할 수 있습니다. 이 작고 강력한 jQuery 플러그인, http://jquery.malsup.com/form/입니다.

    샘플 : 당신이 jQuery를 사용하면 업로드 파일을 쉽게 할 수 있습니다. 이 작고 강력한 jQuery 플러그인, http://jquery.malsup.com/form/입니다.

    var $bar   = $('.ProgressBar');
    $('.Form').ajaxForm({
      dataType: 'json',
    
      beforeSend: function(xhr) {
        var percentVal = '0%';
        $bar.width(percentVal);
      },
    
      uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        $bar.width(percentVal)
      },
    
      success: function(response) {
        // Response
      }
    });
    

    나는 그것이 도움이 될 것입니다 희망


  21. 21.당신이 사용할 수있는

    당신이 사용할 수있는

    $(function() {
        $("#file_upload_1").uploadify({
            height        : 30,
            swf           : '/uploadify/uploadify.swf',
            uploader      : '/uploadify/uploadify.php',
            width         : 120
        });
    });
    

    데모


  22. 22.사용을 base64로 변환 파일 | HTML5의 readAsDataURL () 또는 일부 base64로 인코더. 여기 바이올린

    사용을 base64로 변환 파일 | HTML5의 readAsDataURL () 또는 일부 base64로 인코더. 여기 바이올린

    var reader = new FileReader();
    
            reader.onload = function(readerEvt) {
                var binaryString = readerEvt.target.result;
                document.getElementById("base64textarea").value = btoa(binaryString);
            };
    
            reader.readAsBinaryString(file);
    

    그런 다음 검색 할 수 있습니다 :

    window.open("data:application/octet-stream;base64," + base64);
    

  23. 23.당신은 (플래시 및 iframe 의존하지 않고) XMLHttpRequest 객체를 사용하여 비동기 업로드를 만들기에 파일 이름과 함께 추가 매개 변수를 전달할 수 있습니다. FormData와 추가 매개 변수 값을 추가 및 업로드 요청을 보냅니다.

    당신은 (플래시 및 iframe 의존하지 않고) XMLHttpRequest 객체를 사용하여 비동기 업로드를 만들기에 파일 이름과 함께 추가 매개 변수를 전달할 수 있습니다. FormData와 추가 매개 변수 값을 추가 및 업로드 요청을 보냅니다.

    var formData = new FormData();
    formData.append('parameter1', 'value1');
    formData.append('parameter2', 'value2'); 
    formData.append('file', $('input[type=file]')[0].files[0]);
    
    $.ajax({
        url: 'post back url',
        data: formData,
    // other attributes of AJAX
    });
    

    또한, Syncfusion 자바 스크립트 UI 파일 업로드는 단순히 이벤트 인수를 사용하여이 시나리오에 대한 솔루션을 제공합니다. 여기 문서를 찾을 수 있으며,이 컨트롤에 대한 자세한 내용은 여기 여기 링크 설명을 입력


  24. 24.여기에 비동기 적으로 파일에 대한 업로드 프로세스를 취급을 찾습니다 https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

    여기에 비동기 적으로 파일에 대한 업로드 프로세스를 취급을 찾습니다 https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

    링크의 샘플

    <?php
    if (isset($_FILES['myFile'])) {
        // Example:
        move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
        exit;
    }
    ?><!DOCTYPE html>
    <html>
    <head>
        <title>dnd binary upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            function sendFile(file) {
                var uri = "/index.php";
                var xhr = new XMLHttpRequest();
                var fd = new FormData();
    
                xhr.open("POST", uri, true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        // Handle response.
                        alert(xhr.responseText); // handle response.
                    }
                };
                fd.append('myFile', file);
                // Initiate a multipart/form-data upload
                xhr.send(fd);
            }
    
            window.onload = function() {
                var dropzone = document.getElementById("dropzone");
                dropzone.ondragover = dropzone.ondragenter = function(event) {
                    event.stopPropagation();
                    event.preventDefault();
                }
    
                dropzone.ondrop = function(event) {
                    event.stopPropagation();
                    event.preventDefault();
    
                    var filesArray = event.dataTransfer.files;
                    for (var i=0; i<filesArray.length; i++) {
                        sendFile(filesArray[i]);
                    }
                }
            }
        </script>
    </head>
    <body>
        <div>
            <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
        </div>
    </body>
    </html>
    

  25. 25.이것은 내 솔루션입니다.

    이것은 내 솔루션입니다.

    <form enctype="multipart/form-data">    
    
        <div class="form-group">
            <label class="control-label col-md-2" for="apta_Description">Description</label>
            <div class="col-md-10">
                <input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
            </div>
        </div>
    
        <input name="file" type="file" />
        <input type="button" value="Upload" />
    </form>
    

    그리고 JS

    <script>
    
        $(':button').click(function () {
            var formData = new FormData($('form')[0]);
            $.ajax({
                url: '@Url.Action("Save", "Home")',  
                type: 'POST',                
                success: completeHandler,
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
        });    
    
        function completeHandler() {
            alert(":)");
        }    
    </script>
    

    제어 장치

    [HttpPost]
    public ActionResult Save(string apta_Description, HttpPostedFileBase file)
    {
        [...]
    }
    

  26. 26.당신은 자바 스크립트에 의해 API를 가져 오기 새로운 사용할 수 있습니다. 이 같이 :

    당신은 자바 스크립트에 의해 API를 가져 오기 새로운 사용할 수 있습니다. 이 같이 :

    function uploadButtonCLicked(){
        var input = document.querySelector('input[type="file"]')
    
        fetch('/url', {
          method: 'POST',
          body: input.files[0]
        }).then(res => res.json())   // you can do something with response
          .catch(error => console.error('Error:', error))
          .then(response => console.log('Success:', response));
    }                               
    

    장점 : 당신이 수입 아무것도하지 않아도 API를 가져 오기는 기본적으로 모든 현대적인 브라우저에서 지원됩니다. 또한, 패치 노트 () 한 후 그 때는 사용하여 처리하는 약속 반환 (핸들 응답 .. 코드 ..) 비동기.


  27. 27.HTML5와 자바 스크립트를 사용하여 업로드 비동기 나는,이 API를 필요로이 완전히 작동하지 않는 당신의 HTML과 함께 업로드 논리를 만들지 만, 그것이 어떻게 작동하는지 보여, 매우 쉽게 당신의 루트에서 호출 엔드 포인트 / 업로드가있을 경우 웹 사이트에이 코드는 당신을 위해 작동합니다 :

    HTML5와 자바 스크립트를 사용하여 업로드 비동기 나는,이 API를 필요로이 완전히 작동하지 않는 당신의 HTML과 함께 업로드 논리를 만들지 만, 그것이 어떻게 작동하는지 보여, 매우 쉽게 당신의 루트에서 호출 엔드 포인트 / 업로드가있을 경우 웹 사이트에이 코드는 당신을 위해 작동합니다 :

    CONST asyncFileUpload = () => { const를 fileinput 함수 = document.getElementById를 ( "파일"); CONST 파일 fileInput.files = [0]; const를 URI = "/ 업로드"; CONST XHR = 새로운 XMLHttpRequest 객체 (); xhr.upload.onprogress = E => { CONST 비율은 e.loaded / e.total =; CONSOLE.LOG (백분율); }; xhr.onreadystatechange = E => { 경우 (4 xhr.readyState === && xhr.status === 200) { 을 console.log ( "파일 업로드"); } }; xhr.open ( "POST", URI, TRUE); xhr.setRequestHeader ( "X-파일 이름"file.name); 위해 xhr.send (파일); }

    파일

    XMLHttpRequest 객체에 대한 일부 추가 정보 :

    자세한 내용은 여기 계속해서 읽어 ...


  28. 28.당신은 어떤 플러그인을 사용하지 않고 자바 스크립트 또는 jQuery를하고 있음을 이용하여 비동기 여러 파일 업로드를 할 수 있습니다. 또한 진행 컨트롤에 파일 업로드의 실시간 진행 상황을 표시 할 수 있습니다. 나는이 좋은 링크를 통해 온 -

    당신은 어떤 플러그인을 사용하지 않고 자바 스크립트 또는 jQuery를하고 있음을 이용하여 비동기 여러 파일 업로드를 할 수 있습니다. 또한 진행 컨트롤에 파일 업로드의 실시간 진행 상황을 표시 할 수 있습니다. 나는이 좋은 링크를 통해 온 -

    서버 측 언어는 C #을하지만 당신은 PHP와 같은 다른 언어로 작업하기위한 몇 가지 수정을 할 수 있습니다.

    업로드 ASP.NET 코어 MVC 파일 :

    보기에서 HTML에서 파일 업로드 컨트롤을 만들 :

    <form method="post" asp-action="Add" enctype="multipart/form-data">
        <input type="file" multiple name="mediaUpload" />
        <button type="submit">Submit</button>
    </form>
    

    이제 컨트롤러 액션 메소드를 만듭니다

    [HttpPost]
    public async Task<IActionResult> Add(IFormFile[] mediaUpload)
    {
        //looping through all the files
        foreach (IFormFile file in mediaUpload)
        {
            //saving the files
            string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path"); 
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }
    }
    

    hostingEnvironment 변수 같은 의존성 주입을 사용하여 상기 제어기에 주입 될 수 IHostingEnvironment 형이다 :

    private IHostingEnvironment hostingEnvironment;
    public MediaController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    

  29. 29.PHP를 들어, https://developer.hyvor.com/php/image-upload-ajax-php-mysql를 찾아

    PHP를 들어, https://developer.hyvor.com/php/image-upload-ajax-php-mysql를 찾아

    HTML

    <html>
    <head>
        <title>Image Upload with AJAX, PHP and MYSQL</title>
    </head>
    <body>
    <form onsubmit="submitForm(event);">
        <input type="file" name="image" id="image-selecter" accept="image/*">
        <input type="submit" name="submit" value="Upload Image">
    </form>
    <div id="uploading-text" style="display:none;">Uploading...</div>
    <img id="preview">
    </body>
    </html>
    

    JAVASCRIPT

    var previewImage = document.getElementById("preview"),  
        uploadingText = document.getElementById("uploading-text");
    
    function submitForm(event) {
        // prevent default form submission
        event.preventDefault();
        uploadImage();
    }
    
    function uploadImage() {
        var imageSelecter = document.getElementById("image-selecter"),
            file = imageSelecter.files[0];
        if (!file) 
            return alert("Please select a file");
        // clear the previous image
        previewImage.removeAttribute("src");
        // show uploading text
        uploadingText.style.display = "block";
        // create form data and append the file
        var formData = new FormData();
        formData.append("image", file);
        // do the ajax part
        var ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                var json = JSON.parse(this.responseText);
                if (!json || json.status !== true) 
                    return uploadError(json.error);
    
                showImage(json.url);
            }
        }
        ajax.open("POST", "upload.php", true);
        ajax.send(formData); // send the form data
    }
    

    PHP

    <?php
    $host = 'localhost';
    $user = 'user';
    $password = 'password';
    $database = 'database';
    $mysqli = new mysqli($host, $user, $password, $database);
    
    
     try {
        if (empty($_FILES['image'])) {
            throw new Exception('Image file is missing');
        }
        $image = $_FILES['image'];
        // check INI error
        if ($image['error'] !== 0) {
            if ($image['error'] === 1) 
                throw new Exception('Max upload size exceeded');
    
            throw new Exception('Image uploading error: INI Error');
        }
        // check if the file exists
        if (!file_exists($image['tmp_name']))
            throw new Exception('Image file is missing in the server');
        $maxFileSize = 2 * 10e6; // in bytes
        if ($image['size'] > $maxFileSize)
            throw new Exception('Max size limit exceeded'); 
        // check if uploaded file is an image
        $imageData = getimagesize($image['tmp_name']);
        if (!$imageData) 
            throw new Exception('Invalid image');
        $mimeType = $imageData['mime'];
        // validate mime type
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($mimeType, $allowedMimeTypes)) 
            throw new Exception('Only JPEG, PNG and GIFs are allowed');
    
        // nice! it's a valid image
        // get file extension (ex: jpg, png) not (.jpg)
        $fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
        // create random name for your image
        $fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
        // Create the path starting from DOCUMENT ROOT of your website
        $path = '/examples/image-upload/images/' . $fileName;
        // file path in the computer - where to save it 
        $destination = $_SERVER['DOCUMENT_ROOT'] . $path;
    
        if (!move_uploaded_file($image['tmp_name'], $destination))
            throw new Exception('Error in moving the uploaded file');
    
        // create the url
        $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
        $domain = $protocol . $_SERVER['SERVER_NAME'];
        $url = $domain . $path;
        $stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
        if (
            $stmt &&
            $stmt -> bind_param('s', $url) &&
            $stmt -> execute()
        ) {
            exit(
                json_encode(
                    array(
                        'status' => true,
                        'url' => $url
                    )
                )
            );
        } else 
            throw new Exception('Error in saving into the database');
    
    } catch (Exception $e) {
        exit(json_encode(
            array (
                'status' => false,
                'error' => $e -> getMessage()
            )
        ));
    }
    

  30. 30.또한 https://uppy.io 같은 것을 사용하여 고려할 수 있습니다.

    또한 https://uppy.io 같은 것을 사용하여 고려할 수 있습니다.

    이 페이지와 이벤트에서 드래그 앤 드롭과 같은 몇 가지 보너스를 멀리 이동 브라우저 충돌 / 색다른 네트워크의 경우 업로드를 재개하고, 예를 들어,에서 가져 오지 않고 파일 업로드를 수행 인스 타 그램. 그것은 오픈 소스 및 / 각도 / 뷰 반응 / jQuery를에 의존하지 않지만, 사용할 수 있습니다. 부인 : 작성자으로 나는 바이어스 해요;)

  31. from https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously by cc-by-sa and MIT license