ajaxfileupload.js를 사용하여 ajax 업로드 파일 구현 php version_jquery

WBOY
풀어 주다: 2016-05-16 16:43:11
원래의
1586명이 탐색했습니다.

PHP와 기타 서버측 스크립트 모두 파일 업로드 기능을 제공하며 구현이 비교적 간단합니다. JavaScript를 사용하여 협력하면 Ajax 파일 업로드를 구현할 수 있습니다. jQuery 자체는 이렇게 단순화된 기능을 제공하지 않지만 이를 달성할 수 있는 플러그인이 많이 있습니다. 그 중 Phpletter.com에서 제공하는 ajaxfileupload.js는 경량 플러그인으로, 작성 방식이 jQuery에서 제공하는 전역 메소드인 $.post()와 매우 유사하여 사용이 간편하고 간편합니다.
하지만 플러그인이 너무 단순화되어 업로드할 파일의 경로를 제공하는 것 외에도 백엔드 서버에 추가 값을 전달할 수 없습니다. 그래서 스크립트를 수정하고 데이터 개체 매개변수를 추가했습니다.

1. 원칙

여기에서는 PHP를 서버 스크립트로 사용하고 있습니다. PHP가 없는 거의 모든 책에서는 move_uploaded_file() 메서드를 사용하여 파일을 업로드하는 방법을 언급하므로 여기서는 자세히 설명하지 않겠습니다. 제가 말씀드리고 싶은 것은 Ajax 업로드의 원리를 활용하라는 것입니다.
저는 jQuery 라이브러리를 사용해왔기 때문에 Ajax를 떠올렸을 때 가장 먼저 $.post() 메서드를 사용해 보고, 각 선택기를 사용하여 파일 파일 상자에 값을 가져온 다음 이를 백그라운드 서버에 제출하는 것이었습니다. . 물론 나중에 이것이 효과가 없다는 것이 밝혀졌습니다. (이 문제 때문에 저도 많은 정보를 확인했고, 온라인에 ASP나 기타 스크립트도 많이 나와 있어서 뭐라고 말해야 할지 모르겠습니다.)
다시 본론으로 돌아가서 Ajax 업로드를 구현하는 것은 어렵지 않으며 방법도 많습니다. 이 글에서 언급한 Phpletter.com의 ajaxfileupload.js 플러그인은 iframe을 사용합니다. 이는 JavaScript 스크립트를 사용하지 않을 때 페이지를 새로 고치지 않고 업로드하는 일반적인 방법이기도 합니다. (이 블로그는 bo-blog 백그라운드에서 로그를 작성하기 위해 이 방법을 사용하고 있습니다.)
ajaxfileupload.js 플러그인도 매우 간단합니다. 먼저 jQuery의 선택기를 사용하여 파일 업로드 상자에서 파일 경로 값을 얻은 다음 동적으로 iframe을 생성하고 그 안에 새 파일 상자를 생성하여 제출할 게시 방법을 제공합니다. 백스테이지까지. 마지막으로 결과를 프론트 데스크에 반환합니다.

2. 사용

ajaxfileupload.js 플러그인을 사용하는 방법은 매우 간단합니다.
프론트엔드 HTML 코드도 비슷합니다:

<script type="text/javascript">
$(#buttonUplod).click(function () {
 $.ajaxFileUpload ({
  url:'doajaxfileupload.php', //你处理上传文件的服务端
  secureuri:false, //与页面处理代码中file相对应的ID值
  fileElementId:'img',
  dataType: 'json', //返回数据类型:text,xml,json,html,scritp,jsonp五种
  success: function (data) {
   alert(data.file_infor);
  }
 })
});
</script>
<input id="img" type="file" size="45" name="img" >
<button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button> 
로그인 후 복사

백엔드 doajaxfileupload.php 스크립트:

<&#63;php
 $upFilePath = "../attachment/";
$ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);
 if($ok === FALSE){
  echo json_encode('file_infor'=>'上传失败');
 }else{
  echo json_encode('file_infor'=>'上传成功');
 }
&#63;> 

로그인 후 복사


테스트를 위해 다음과 유사한 방법을 사용하여 전달된 변수 값을 저장할 수 있습니다.

$file_info = var_export($_FILES,true);
$ok = file_put_contents("../attachment/file_info.txt",$file_info);
if ($ok) exit(json_encode('file_infor'=>'업로드 성공'));
종료 (json_encode('file_infor'=>'업로드 실패'));


※ 참고
HTML 코드 파일 상자의 태그를 참고하세요:

1. id='img'는 ajaxfileupload.js 플러그인의 fileElementId:'img'를 식별하는 데 사용됩니다. jQuery 선택기는 이 문자열을 사용하여 텍스트 상자의 값을 얻습니다. 2. post를 통해 백그라운드 스크립트에 제출할 때 name='img'가 사용됩니다. PHP는 $_FILES['img']를 통해 업로드된 파일의 데이터를 읽습니다.

그래서 이 두 가치는 필수불가결하고 혼동될 수 없습니다.

3. 추가 매개변수 지원

가끔 백그라운드에서 특정 변수에 따라 업로드된 파일을 처리해야 하는 경우가 있습니다. 예를 들어 업데이트 파일이 있습니다. 이때 동일한 스테이지에 몇 가지 추가 매개변수를 전달해야 합니다. 그래서 ajaxfileupload.js 플러그인을 수정했습니다:

addOtherRequestsToForm: function(form,data)
{
 // add extra parameter
 var originalElement = $('<input type="hidden" name="" value="">');
 for (var key in data) {
  name = key;
  value = data[key];
  var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
  $(cloneElement).appendTo(form);
 }
 return form;
}, 

ajaxFileUpload: function(s) {
 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout  
 s = jQuery.extend({}, jQuery.ajaxSettings, s);
 var id = new Date().getTime()    
 var form = jQuery.createUploadForm(id, s.fileElementId);
 if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
 var io = jQuery.createUploadIframe(id, s.secureuri); 

로그인 후 복사
빨간색으로 표시한 부분이 제가 추가한 내용입니다. 이러한 방식으로 다음과 유사한 코드를 통해 프런트엔드 HTML 부분에 추가 매개변수를 전달할 수 있습니다.

url:'doajaxfileupload.php', //업로드된 파일을 처리하는 서버

secureuri:false, //페이지 처리 코드에서 파일에 해당하는 ID 값
data:{'test':'test','ok':'ok'}, //객체로 전송되며, 컨텐츠 부분에 자바스크립트 변수값을 입력할 수 있습니다
fileElementId:'img',

백그라운드 처리 스크립트는 다음과 같습니다.

array_push($_FILES,$_REQUEST);
$file_info = var_export($_FILES,true);
$ok = file_put_contents("../attachment/file_info.txt",$file_info);
if ($ok) exit(json_encode('file_infor'=>'上传成功'));
exit (json_encode('file_infor'=>'上传失败')); 

로그인 후 복사
원리는 매우 간단하다는 것을 알 수 있습니다. 즉, iframe 아래의 양식에 추가 데이터 개체 콘텐츠를 추가하고 이를 배경 PHP 스크립트에 전달한 후 다음과 같은 변수를 사용하여 이러한 값을 얻는 것입니다. $_요청.

백그라운드 출력에 유지되는 file_info.txt의 내용은 다음과 같습니다.

배열(

'파일' =>
배열(
'이름' => 'firefox-java.txt',
'유형' => '텍스트/일반',
'tmp_name' => 'D:\Tools\xampp\tmp\phpED45.tmp',
'오류' => 0,
'크기' => 250,
),
0 =>
배열(
'테스트' => '테스트',
'알았어' => '알았어',
'PHPSESSID' => 'e379fd4fb2abca6e802a1302805a5535',
),
)

ajaxfileupload.js:

jQuery.extend({
  createUploadIframe: function(id, uri)
 {
  //create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; 

document.body.appendChild(io); 

return io  
  },
  createUploadForm: function(id, fileElementId)
 {
 //create form 
 var formId = 'jUploadForm' + id;
 var fileId = 'jUploadFile' + id;
 var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); 
 var oldElement = $('#' + fileElementId);
 var newElement = $(oldElement).clone();
 $(oldElement).attr('id', fileId);
 $(oldElement).before(newElement);
 $(oldElement).appendTo(form);
 //set attributes
 $(form).css('position', 'absolute');
 $(form).css('top', '-1200px');
 $(form).css('left', '-1200px');
 $(form).appendTo('body'); 
 return form;
  },
 addOtherRequestsToForm: function(form,data)
 {
 // add extra parameter
 var originalElement = $('<input type="hidden" name="" value="">');
 for (var key in data) {
  name = key;
  value = data[key];
  var cloneElement = originalElement.clone();
  cloneElement.attr({'name':name,'value':value});
  $(cloneElement).appendTo(form);
 }
 return form;
 }, 

  ajaxFileUpload: function(s) {
    // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 
    s = jQuery.extend({}, jQuery.ajaxSettings, s);
    var id = new Date().getTime()    
 var form = jQuery.createUploadForm(id, s.fileElementId);
 if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
 var io = jQuery.createUploadIframe(id, s.secureuri);
 var frameId = 'jUploadFrame' + id;
 var formId = 'jUploadForm' + id; 
    // Watch for a new set of requests
    if ( s.global && ! jQuery.active++ )
 {
  jQuery.event.trigger( "ajaxStart" );
 }      
    var requestDone = false;
    // Create the request object
    var xml = {} 
    if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
    // Wait for a response to come back
    var uploadCallback = function(isTimeout)
 {  
  var io = document.getElementById(frameId);
try
  {  
  if(io.contentWindow)
  {
   xml.responseText = io.contentWindow.document.body&#63;io.contentWindow.document.body.innerHTML:null;
 xml.responseXML = io.contentWindow.document.XMLDocument&#63;io.contentWindow.document.XMLDocument:io.contentWindow.document;
  }else if(io.contentDocument)
  {
   xml.responseText = io.contentDocument.document.body&#63;io.contentDocument.document.body.innerHTML:null;
 xml.responseXML = io.contentDocument.document.XMLDocument&#63;io.contentDocument.document.XMLDocument:io.contentDocument.document;
  }   
}catch(e)
  {
  jQuery.handleError(s, xml, null, e);
  }
if ( xml || isTimeout == "timeout")
  {  
requestDone = true;
var status;
try {
status = isTimeout != "timeout" &#63; "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
   {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );  
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
  {
status = "error";
jQuery.handleError(s, xml, status, e);
} 

// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); 

// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); 

// Process result
if ( s.complete )
s.complete(xml, status); 

jQuery(io).unbind() 

setTimeout(function()
     { try
     {
      $(io).remove();
      $(form).remove(); 
     } catch(e)
     {
      jQuery.handleError(s, xml, null, e);
     }     

     }, 100) 

xml = null 

}
    }
    // Timeout checker
    if ( s.timeout > 0 )
 {
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
    }
    try
 {
      // var io = $('#' + frameId);
  var form = $('#' + formId);
  $(form).attr('action', s.url);
  $(form).attr('method', 'POST');
  $(form).attr('target', frameId);
if(form.encoding)
  {
form.encoding = 'multipart/form-data';  
}
else
  {  
form.enctype = 'multipart/form-data';
}  
$(form).submit(); 

    } catch(e)
 {  
jQuery.handleError(s, xml, null, e);
    }
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
    }
    else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
    }  
    return {abort: function () {}}; 

  }, 

  uploadHttpData: function( r, type ) {
    var data = !type;
    data = type == "xml" || data &#63; r.responseXML : r.responseText;
    // If the type is "script", eval it in global context
    if ( type == "script" )
jQuery.globalEval( data );
    // Get the JavaScript object, if JSON is used.
    if ( type == "json" )
eval( "data = " + data );
    // evaluate scripts within html
    if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
  //alert($('param', data).each(function(){alert($(this).attr('value'));}));
    return data;
  }
}) 
로그인 후 복사
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!