카테고리 없음

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

행복을전해요 2021. 2. 16. 10:16

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 "move_uploaded_file function failed";
                }
                ?>
                

다음은 예제 애플리케이션입니다.

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

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

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

Jquery를 사용하여 비동기 적으로 파일을 업로드하려면 아래 단계를 사용하십시오.

단계 1 프로젝트에서 Nuget 관리자를 열고 패키지를 추가합니다 (jquery fileupload (검색 상자에 작성하면 나타나서 설치합니다.)) URL : https://github.com/blueimp/jQuery-File- 업로드

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

jquery.ui.widget.js

jquery.iframe-transport.js

jquery.fileupload.js

3 단계 아래 코드에 따라 파일 업로드 컨트롤을 작성합니다.

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

4 단계 js 메소드를 아래와 같이 uploadFile로 작성합니다.

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

Jquery없는 현대적인 접근 방식 사용자가 파일을 선택할 때 반환되는 FileList 객체 <input type="file">를 사용한 다음 Fetch사용 하여 FormData 객체를 감싸는 FileList를 게시하는 것 입니다.

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

당신은 데모 작업과 함께 해결 솔루션을 볼 수 있습니다 여기에 당신이 미리 서버에 폼 파일을 제출할 수 있습니다. 귀하의 경우 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");
                                                           
                                                                });
                                                                   });
                                                                   });
                                                                   

자세히보기

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

샘플 : 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
                                  }
                                  });
                                  

도움이 되길 바랍니다

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

당신이 사용할 수있는

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

데모

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

HTML5의 readAsDataURL () 또는 일부 base64 인코더를 사용하여 파일을 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);
-------------------

XMLHttpRequest를 사용하여 비동기 업로드를 만들 때 파일 이름과 함께 추가 매개 변수를 전달할 수 있습니다 (플래시 및 iframe 종속성 없음). 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 JavaScript UI 파일 업로드는 단순히 이벤트 인수를 사용하여이 시나리오에 대한 솔루션을 제공합니다. 여기에서 문서를 찾을 수 있으며이 컨트롤에 대한 자세한 내용은 여기에 링크 설명을 입력 하십시오.

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

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

이것이 내 해결책입니다.

<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)
{
    [...]
    }
    
-------------------

JavaScript로 최신 Fetch 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));
                                    }                               
                                    

장점 : Fetch API는 기본적으로 모든 최신 브라우저에서 지원 되므로 아무것도 가져올 필요가 없습니다. 또한 fetch ()는 비동기 적 으로 사용하여 처리되는 Promise반환합니다 .then(..code to handle response..).

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

HTML5JavaScript를 사용하여 비동기 업로드는 매우 쉽습니다. html과 함께 업로드 로직을 생성합니다. 이것은 API가 필요하므로 완전히 작동하지 않지만 /upload웹 사이트의 루트에서 호출 엔드 포인트가있는 경우 작동 방식을 보여줍니다 . 이 코드는 다음과 같이 작동합니다.

const asyncFileUpload = () => {
      const fileInput = document.getElementById("file");
        const file = fileInput.files[0];
          const uri = "/upload";
            const xhr = new XMLHttpRequest();
              xhr.upload.onprogress = e => {
                  const percentage = e.loaded / e.total;
                      console.log(percentage);
                        };
                          xhr.onreadystatechange = e => {
                              if (xhr.readyState === 4 && xhr.status === 200) {
                                    console.log("file uploaded");
                                        }
                                          };
                                            xhr.open("POST", uri, true);
                                              xhr.setRequestHeader("X-FileName", file.name);
                                                xhr.send(file);
                                                }
<form>
      <span>File</span>
        <input type="file" id="file" name="file" size="10" />
          <input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
          </form>
스 니펫 확장

또한 XMLHttpReques에 대한 추가 정보 :

XMLHttpRequest 객체

모든 최신 브라우저는 XMLHttpRequest 객체를 지원합니다. XMLHttpRequest 객체는이면에서 웹 서버와 데이터를 교환하는 데 사용할 수 있습니다. 이는 전체 페이지를 다시로드하지 않고도 웹 페이지의 일부를 업데이트 할 수 있음을 의미합니다.


XMLHttpRequest 개체 만들기

모든 최신 브라우저 (Chrome, Firefox, IE7 +, Edge, Safari, Opera)에는 기본 제공 XMLHttpRequest 객체가 있습니다.

XMLHttpRequest 객체 생성을위한 구문 :

변수 = new XMLHttpRequest ();


도메인 간 액세스

보안상의 이유로 최신 브라우저는 도메인 간 액세스를 허용하지 않습니다.

즉,로드하려는 웹 페이지와 XML 파일이 모두 동일한 서버에 있어야합니다.

W3Schools의 예제는 W3Schools 도메인에있는 모든 열린 XML 파일입니다.

자신의 웹 페이지 중 하나에서 위의 예를 사용하려면로드하는 XML 파일이 자신의 서버에 있어야합니다.

자세한 내용은 여기에서 계속 읽을 수 있습니다 .

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

JavaScript 또는 jQuery를 사용하여 비동기 다중 파일 업로드를 수행 할 수 있으며 플러그인을 사용하지 않고이를 수행 할 수 있습니다. 진행률 컨트롤에서 파일 업로드의 실시간 진행률을 표시 할 수도 있습니다. 2 개의 멋진 링크를 발견했습니다.

  1. 진행률 표시 줄이있는 ASP.NET Web Forms 기반 다중 파일 업로드 기능
  2. jQuery에서 만든 ASP.NET MVC 기반 다중 파일 업로드

서버 측 언어는 C #이지만 PHP와 같은 다른 언어에서 작동하도록 일부 수정을 수행 할 수 있습니다.

파일 업로드 ASP.NET Core 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;
    }
    
-------------------

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>
            

자바 스크립트

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

https://uppy.io 와 같은 것을 사용할 수도 있습니다 .

페이지에서 이동하지 않고 파일 업로드를 수행하고 드래그 앤 드롭, 브라우저 충돌 / 불안정한 네트워크의 경우 업로드 재개, 예를 들어 Instagram에서 가져 오기와 같은 몇 가지 보너스를 제공합니다. 오픈 소스이며 jQuery / React / Angular / Vue에 의존하지 않지만 함께 사용할 수 있습니다. 면책 조항 : 제작자로서 나는 편견입니다.)