etc./StackOverFlow

jQuery를 사용하여 어떻게 파일을 비동기적으로 업로드할 수 있습니까?

청렴결백한 만능 재주꾼 2021. 10. 9. 02:26
반응형

질문자 :Sergio del Amo


jQuery를 사용하여 파일을 비동기식으로 업로드하고 싶습니다.

 $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("Data Uploaded: "); } }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/>

업로드되는 파일 대신 파일 이름만 가져옵니다. 이 문제를 해결하려면 어떻게 해야 합니까?



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 구성요소 중 일부는 모든 브라우저에서 사용할 수 있는 것은 아니므 로 Google Chrome에서 시도해 보십시오.


olanod

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

file API로 이해해야 할 중요한 점 은 IE 10까지 지원되지 않았다는 것입니다. 목표로 하는 특정 시장이 이전 버전의 Windows에 대해 평균보다 높은 경향이 있는 경우 해당 시장에 액세스하지 못할 수 있습니다.

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

이 편집을 기준으로 2019년입니다. 제 초기 답변 후 거의 11년입니다. IE9 이하 버전은 전 세계적으로 약 1% 수준이지만 여전히 사용량이 많은 클러스터가 있습니다.

피쳐가 -whatever이에서 중요한 멀리 걸릴, 사용자가 사용하는 브라우저 확인. 그렇게 하지 않으면 고객에게 제공할 결과물에서 "저를 위해 일하는 것"이 왜 충분하지 않은지에 대한 빠르고 고통스러운 교훈을 배우게 될 것입니다. caniuse 는 유용한 도구이지만 인구 통계를 어디에서 가져오는지 확인하세요. 그들은 당신과 일치하지 않을 수 있습니다. 이것은 기업 환경보다 결코 사실이 아닙니다.

2008년부터 내 대답은 다음과 같다.


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

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

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

또는 Java/Flash 솔루션을 사용하십시오. 그들은 자신의 게시물로 할 수 있는 일에 훨씬 더 유연합니다...


Oli

이를 위해 Fine Uploader 플러그인을 사용하는 것이 좋습니다. JavaScript 코드는 다음과 같습니다.

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

pixxaar

참고: 이 답변은 구식이며 이제 XHR을 사용하여 파일을 업로드할 수 있습니다.


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


Mattias

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

비동기 파일 업로드

HTML5로

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

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가 지원되지 않는 경우( File API 없음) 유일한 순수 JavaScript 솔루션( Flash 또는 기타 브라우저 플러그인 없음)은 XMLHttpRequest 객체를 사용하지 않고 비동기 요청을 에뮬레이트할 수 있는 숨겨진 iframe 기술입니다.

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

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

이 경우 iframe 기술 을 사용 $.ajax() 메서드만 사용하여 파일보낼 수 있는 jQuery Ajax 전송 도 제공하는 Bifröst 와 같은 래퍼 플러그인을 사용하는 것을 선호할 수 있습니다.

 $.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에서 다양한 대체에 이르는 전체 스택과 프로세스를 쉽게 해주는 몇 가지 유용한 기능이 포함되어 있습니다. 필요와 요구 사항에 따라 베어 구현 또는 이 플러그인 중 하나를 고려할 수 있습니다.


404

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

Jordan Feldstein

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

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 파일 업로드의 핵심 기능입니다. 사실 자바스크립트.


Techie

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

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

mpen

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

Zayn Ali

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

플러그인, JavaScript 또는 HTML 이외의 다른 형태의 "마법"을 사용하고 싶지 않은 경우입니다. 물론 이것을 JavaScript와 결합하거나 무엇을 가지고 있는지...

 <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 의 내용을 읽은 다음 사용자에게 출력할 수도 있습니다.

Chrome, iFrame 및 onLoad

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

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

Chrome에서 작동하는 유일한 솔루션은 쿠키를 사용하는 것이었습니다.

업로드/다운로드가 시작될 때 기본적으로 그렇게 하려면:

  • [클라이언트 측] 쿠키의 존재를 찾는 간격 시작
  • [서버 측] 파일 데이터로 필요한 모든 작업 수행
  • [서버 측] 클라이언트 측 간격에 대한 쿠키 설정
  • [클라이언트 측] 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 콜백을 트리거합니다.


ArtisticPhoenix

저는 이것을 Rails 환경에서 작성했습니다 . 경량 jQuery 형식 플러그인을 사용하는 경우 JavaScript의 5줄 정도에 불과합니다.

remote_form_for 가 여러 부분으로 구성된 양식 제출을 이해하지 못하기 때문에 AJAX 업로드가 작동하도록 하는 것입니다. Rails가 AJAX 요청으로 다시 찾는 파일 데이터를 보내지 않을 것입니다.

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

이에 대한 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와 함께 지난 몇 주 동안 이것을 사용해 왔으며 챔피언처럼 작동했습니다.


wbharding

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

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

  • 브라우저 간 -- IE7+, Firefox, Chrome, Safari, Opera에서 작동
  • HTML5가 아닌 브라우저에서도 여러 동시 업로드 지원
  • 플래시 또는 외부 CSS 없음 -- 단 하나의 5Kb Javascript 파일
  • 선택 사항, 완전한 크로스 브라우저 진행률 표시줄에 대한 기본 제공 지원(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 } });

user1091949

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


Darryl Hein

다음은 플러그인 없이 파일을 업로드하는 방법에 대한 또 다른 솔루션입니다.

간단한 JavascriptAJAX 사용 (진행률 표시줄 포함)

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

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


Siddhartha Chowdhury

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

farnoush resa

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

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


Vivek Aasaithambi

Jquery 가 없는 현대적인 접근 방식은 사용자가 파일을 선택할 때 <input type="file"> 에서 반환된 FileList 객체를 사용한 다음 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 }); });

Alister

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

프로젝트의 1 단계 개방 Nuget 관리자와 추가 패키지 (JQuery와 파일 업로드 (가 와서 설치됩니다 만 검색 상자에 작성해야합니다).) 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 컨트롤러와 Action을 작성합니다.

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

ashish

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

자세히 보기


Daniel Nyamasyo

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

도움이 되기를 바랍니다.


MEAbid

당신이 사용할 수있는

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

데모


Amit

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

tnt-rox

플래시 및 iframe 종속성 없이 XMLHttpRequest를 사용하여 비동기 업로드를 만들 때 파일 이름과 함께 추가 매개변수를 전달할 수 있습니다. FormData에 추가 매개변수 값을 추가하고 업로드 요청을 보냅니다.


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

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


Karthik Ravichandran

이것이 내 솔루션입니다.

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

Erick Lanford Xenes

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>

Allende

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()는 .then(..code to handle response..) 사용하여 응답을 비동기식으로 처리하여 처리되는 Promise를 반환합니다.


BlackBeard

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 객체 생성 구문:

변수 = 새로운 XMLHttpRequest();


도메인 간 액세스

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

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

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

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

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


Alireza

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

Supun Kavinda

플러그인을 사용하지 않고 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; }

Joe Clinton

오래된 질문이지만 여전히 정답이 없으므로 다음을 수행합니다.

jQuery-File-Upload 를 사용해 보셨습니까?

다음은 문제를 해결할 수 있는 위 링크의 예입니다.

 $('#fileupload').fileupload({ add: function (e, data) { var that = this; $.getJSON('/example/url', function (result) { data.formData = result; // eg {id: 123} $.blueimp.fileupload.prototype .options.add.call(that, e, data); }); } });

lat94

출처 : http:www.stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery

반응형