jQuery와 비동기적으로 파일을 업로드하려면 어떻게 해야 합니까?
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, Iframes 또는 플러그인을 사용하고 싶지 않아 몇 가지 조사 끝에 해결 방법을 생각해 냈습니다.
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에서 사용해 보십시오.
2019년 업데이트:여전히 사용자 정보에서 사용하는 브라우저에 따라 다릅니다.
" HTML5 "" HTML5에서 해야 할 한 점fileAPI는 IE 10까지는 지원되지 않았습니다.목표로 하는 특정 시장이 이전 버전의 Windows에 대한 평균보다 높은 성향을 가지고 있는 경우 해당 시장에 액세스하지 못할 수 있습니다.
2017년 기준으로 브라우저의 약 5%가 IE 6, 7, 8, 9 중 하나입니다.대기업(예를 들어, B2B 툴이나 트레이닝용으로 제공하는 것 등)으로 향하는 경우, 그 수는 급증할 가능성이 있습니다.2016년에 저는 IE8을 사용하는 회사의 60% 이상의 기계와 거래했습니다.
제가 처음 답변을 드린지 11년이 다 되어가는 2019년입니다.IE9 이하가 전 세계적으로 1%대 안팎이지만 여전히 더 높은 사용률을 보이는 클러스터가 있습니다.
여기서 중요한 포인트는 어떤 기능을 사용하든 사용자가 사용하는 브라우저를 체크하는 것입니다.그렇지 않으면 고객에게 제공하는 자료에서 '나에게 도움이 되는 일'이 왜 충분하지 않은지에 대한 뼈아픈 교훈을 얻을 수 있습니다. 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 플러그인입니다.
장래의 독자를 위해서 정리합니다.
비동기 파일 업로드
HTML5 지원
를 사용하여 jQuery를 사용하여 파일을 업로드할 수 있습니다.$.ajax()메서드(FormData 및 File API 지원 여부)를 지정합니다(HTML5 기능 모두).
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 없음), 다른 순수한 JavaScript 솔루션(플래시 또는 다른 브라우저 플러그인 없음)은 숨겨진 iframe 기술뿐이며, 이를 통해 XMLHttpRequest 개체를 사용하지 않고도 비동기 요청을 에뮬레이트할 수 있습니다.
파일 입력으로 iframe을 폼의 대상으로 설정하는 것으로 구성됩니다.사용자가 요청을 전송하고 파일이 업로드되지만 응답은 메인 페이지를 다시 렌더링하지 않고 iframe 내에 표시됩니다.iframe을 숨기면 프로세스 전체가 사용자에게 투명해지고 비동기 요청이 에뮬레이트됩니다.
올바르게 실행되면 거의 모든 브라우저에서 동작하지만 iframe에서 응답을 얻는 방법과 같은 몇 가지 주의사항이 있습니다.
이 경우 iframe 기술을 사용하지만 jQuery Ajax 트랜스포트도 제공하는 Bifröst와 같은 래퍼 플러그인을 사용하는 것이 좋습니다.$.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에 .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 레 、 php 、 can can can can can can can 。추가 는 가가 can can can로 할 수 .$_POSTdata.data.data.data.contract.
여기에서는 플러그인과 같은 것을 사용하지 않습니다.원하는 대로 코드를 변경할 수 있습니다.당신은 여기서 맹목적으로 코드화하고 있지 않아요.이것은 모든 jQuery 파일 업로드의 핵심 기능입니다.사실 Javascript.
바닐라 JavaScript로 쉽게 할 수 있습니다.제 현재 프로젝트의 일부를 소개합니다.
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; }
Javascript:
$(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 이외의 다른 형태의 "매직"을 사용하고 싶지 않은 경우입니다. 물론 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>
iframe의 수 .onLoad서버 오류 또는 성공 응답을 확인한 후 사용자에게 출력합니다.
Chrome, iFrames 및 onLoad
-참고- 업로드/다운로드 시 UI 차단 설정 방법에 관심이 있는 경우에만 계속 읽으면 됩니다.
현재 Chrome은 파일 전송에 사용될 때 iframe에 대한 onLoad 이벤트를 트리거하지 않습니다.Firefox, IE 및 Edge는 모두 파일 전송을 위해 온로드 이벤트를 실행합니다.
Chrome에 맞는 유일한 해결책은 쿠키를 사용하는 것이었습니다.
기본적으로 업로드/다운로드가 시작될 때 이를 수행하려면 다음 절차를 따릅니다.
- [클라이언트 측] 쿠키 존재 여부를 찾는 간격을 시작합니다.
- [서버측] 파일 데이터를 사용하여 필요한 작업을 수행할 수 있습니다.
- [서버측] 클라이언트측 인터벌 쿠키 설정
- [클라이언트 측] 간격은 쿠키를 표시하고 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');
});
그리고 서버 측에서 파일 데이터 전송 직전에 cookie를 만듭니다.
setcookie('iDownloader', true, time() + 30, "/");
쿠키가 되고 나서, 「가 됩니다.onComplete콜백
저는 이것을 레일즈 환경에서 작성했습니다.Lightweight jQuery-form 플러그인을 사용하는 경우 JavaScript는 5줄 정도밖에 되지 않습니다.
AJAX로 입니다.remote_form_for다중 부품 양식 제출을 이해할 수 없습니다.레일즈 에이잭스
여기서 jQuery 형식의 플러그인이 실행됩니다.
레일 코드는 다음과 같습니다.
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
연관된 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 Javascript 파일 1개만
- (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
}
});
가 은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.<form>【iFrame】【iFrame】【iFrame】【iFrame】.그런 다음 iFrame은 JS를 실행하여 완료되었음을 사용자에게 표시할 수 있습니다(페이지 로드 시).
여기 (플러그인 없이) 파일을 업로드하는 또 다른 솔루션이 있습니다.
단순 Javascript 및 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";
}
?>
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);
}
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를 사용하지 않는 현대적 접근법은 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
});
});
Jquery와 비동기적으로 파일을 업로드하려면 다음 단계를 사용합니다.
스텝 1 프로젝트에서 Nuget 매니저를 열고 패키지를 추가합니다(jquery file upload(검색 상자에 입력하기만 하면 해당 파일이 표시되며 설치됩니다). URL : https://github.com/blueimp/jQuery-File-Upload
스텝 2 위의 패키지를 실행하여 프로젝트에 이미 추가된 HTML 파일에 다음 스크립트를 추가합니다.
jquery.ui를 클릭합니다.widget.syslog
jquery.iframe-display.displays.disples
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 Ready function의 호출 요소 파일을 업로드하여 다음과 같이 프로세스를 시작합니다.
$(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
};
}
}
여기에서는 작업 데모를 통해 해결된 솔루션을 볼 수 있습니다.이 데모에서는 폼 파일을 미리 보고 서버에 제출할 수 있습니다.이 경우 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>
제출되는 데이터는 폼 데이터입니다.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");
});
});
});
이게 제 해결책입니다.
<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)
{
[...]
}
사용할 수 있습니다.
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
예: 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
}
});
도움이 되었으면 합니다.
| 를 사용하여 파일을 base64로 변환합니다.HTML5의 readAsDataURL() 또는 일부 base64 인코더.여기를 만지작거리다
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
다음으로 검색:
window.open("data:application/octet-stream;base64," + base64);
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 파일 업로드에서는 event 인수를 사용하는 것만으로 이 시나리오에 대한 솔루션을 제공합니다.매뉴얼은 이쪽에서 보실 수 있습니다.이 컨트롤에 대한 자세한 내용은 이쪽에서 링크 설명을 입력해 주세요.
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>
새로운 Fetch API by JavaScript를 사용할 수 있습니다.다음과 같이 합니다.
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를 반환하며, Promise는 다음 명령을 사용하여 처리됩니다..then(..code to handle response..)비동기적으로
HTML5와 JavaScript를 사용하면 비동기 업로드는 매우 간단합니다.저는 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>
XMLHttpRequires에 대한 자세한 내용은 다음과 같습니다.
XMLHttpRequest 객체
최신 브라우저는 모두 XMLHttpRequest 개체를 지원합니다.XMLHttpRequest 개체를 사용하여 백그라운드에서 웹 서버와 데이터를 교환할 수 있습니다.즉, 전체 페이지를 다시 로드하지 않고 웹 페이지의 일부를 업데이트할 수 있습니다.
XMLHttpRequest 객체 생성
모든 최신 브라우저(Chrome, Firefox, IE7+, Edge, Safari, Opera)에는 XMLHttpRequest 개체가 내장되어 있습니다.
XMLHttpRequest 개체를 만들기 위한 구문:
변수 = new XMLHttpRequest();
도메인 간 액세스
보안상의 이유로 최신 브라우저는 도메인 간 액세스를 허용하지 않습니다.
즉, 웹 페이지와 로드하려고 하는 XML 파일이 모두 같은 서버상에 있어야 합니다.
W3Schools의 예는 W3Schools 도메인에 있는 모든 XML 파일을 엽니다.
자신의 웹 페이지 중 하나에서 위의 예를 사용하려면 로드하는 XML 파일이 자신의 서버에 있어야 합니다.
자세한 내용은 여기를 참조하십시오.
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()
)
));
}
JavaScript 또는 jQuery를 사용하여 Asynchronous Multiple File을 업로드하거나 플러그인을 사용하지 않고 업로드할 수 있습니다.또한 진행률 제어에서 파일 업로드의 실시간 진행률을 표시할 수도 있습니다.2개의 멋진 링크를 발견했습니다.
서버 측 언어는 C#이지만 PHP와 같은 다른 언어에서 작동하도록 수정할 수 있습니다.
파일 업로드 ASP.NET 코어 MVC:
View create file upload control in 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);
}
}
}
호스트 환경 변수는 다음과 같이 종속성 주입을 사용하여 컨트롤러에 주입할 수 있는 IHosting Environment 유형입니다.
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
오래된 질문이지만 정답이 없기 때문에 다음과 같습니다.
jQuery-File-Upload를 사용해 보셨습니까?
위의 링크에서 문제를 해결할 수 있는 예를 다음에 제시하겠습니다.
$('#fileupload').fileupload({
add: function (e, data) {
var that = this;
$.getJSON('/example/url', function (result) {
data.formData = result; // e.g. {id: 123}
$.blueimp.fileupload.prototype
.options.add.call(that, e, data);
});
}
});
언급URL : https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery
'source' 카테고리의 다른 글
| 캐스케이드 타입의 차이점은 무엇입니까?JPA에서 REMOVE 및 orphanRemoval? (0) | 2022.11.12 |
|---|---|
| Python이 해석되면 .pyc 파일이 뭐죠? (0) | 2022.11.12 |
| 마리아에서 테이블 2개를 완전히 연결하다DB (0) | 2022.11.12 |
| System.out.println()을 짧게 하는 방법 (0) | 2022.11.12 |
| 특징과 인터페이스 (0) | 2022.11.12 |