php+ajax图片文件异步上传示例代码

发布时间:2019-09-18编辑:脚本学堂
本文介绍了php与ajax实现图片文件上传的方法,异步文件上传功能有几种,比较多见的如使用iframe框架形式,ajax功能效果,以及flash+php功能。

常用的异步文件上传功能有几种,比较多见的如使用iframe框架形式,ajax功能效果,以及flash+php功能。

本节脚本小编为大家介绍ajax与iframe实现异步文件上传的功能的例子。

方法一,利用jquery ajaxfileupload.js实现文件上传
实现无刷新式的文件上传。可采用IFRAME文件上传原理。
实际上在用PHP上传文件时。只能用$_FILES形式,但是若只是单一的用JS方式取其ID,如<input id='img' type='file'>..document.getElementById('img').value或者jquery形式的$("#img")都是不能正真实际上传的(但是还是有很多人这样做,刚开始时我也是)。
可是功能上又要要求实现所谓的“异步上传”,怎么办呢?只能借助于第三方的组件,或自己写一个(在网页里嵌入一个IFRAME)。
但如果是考虑开发时间,建议用第三方的,这里有一个不错的jQuery 的Ajax文件上传的组件,即“ajaxfileupload.js",基内容为:
 

复制代码 代码示例:

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

}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);

return jQuery('#' + frameId).get(0);
    }, // www.jb200.com
    createUploadForm: function(id, fileElementId)
 {
//create form 
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); 
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//添加参数支持
if(data){
$.each(data,function(key,value){
 $("<input type='hidden' name='"+key+"' value='"+value+"'/>").appendTo(form);
})
}
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
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,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?io.contentWindow.document.body.innerHTML:null;
  xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
 
 }else if(io.contentDocument)
 {
 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
 xml.responseXML = io.contentDocument.document.XMLDocument?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" ? "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
 {
jQuery(io).remove();
jQuery(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 form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
            if(form.encoding)
{
 jQuery(form).attr('encoding', 'multipart/form-data');     
            }
            else

 jQuery(form).attr('enctype', 'multipart/form-data');
            }
            jQuery(form).submit();

        } catch(e)
{
            jQuery.handleError(s, xml, null, e);
        }

jQuery('#' + frameId).load(uploadCallback );
        return {abort: function () {}}; 

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? 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();

        return data;
    }
})

过程:
(1 )前端文件的代码: test.php
 

复制代码 代码示例:
<script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="ajaxfileupload.js"></script>
 <script type="text/javascript">
 function ajaxFileUpload()
{
$.ajaxFileUpload
(
  {
 url:'doajaxfileupload.php', //你处理上传文件的服务端
 secureuri:false,
 fileElementId:'img',
 dataType: 'json',
 success: function (data)
 {
alert(data.file_infor);
 }
 }
 )
  return false;
  }
  </script>
 

相应的HTML为:
 

复制代码 代码示例:
<input id="img" type="file" size="45" name="img" class="input">
  <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
 

这样客户端就完成了。

(2) 在服务器端的doajaxfileupload.php
此处为了简便的检测是否真正的传值过来了,你可以将它存起来了。
 

复制代码 代码示例:
$file_infor = var_export($_FILES,true);
 file_put_contents("d:file_infor.php".$file_infor);
 

这样打来刚生成的file_infor.php文件时,又看到了熟悉的信息了:
 

复制代码 代码示例:
array(
 'name'=>'lamp.jpg',
 'type'=>'image/pjpeg',
 'tmp_name'=>'c:windowstempphpFA.tmp',
 'error'=>0,
 'size'=>3127
)
 

当然,真正的处理类于这样的:
 

复制代码 代码示例:
<?php
  $upFilePath = "d:/";
  $ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);
if($ok === FALSE){
 echo json_encode('file_infor'=>'上传失败');
}else{
 echo json_encode('file_infor'=>'上传成功');
}
?>

方法二,利用iframe框架上传图片
html代码:
 

复制代码 代码示例:
<div class="frm">
  <form name="uploadFrom" id="uploadFrom" action="upload.php" method="post"  target="tarframe" enctype="multipart/form-data">
   <input type="file" id="upload_file" name="upfile">
  </form>
  <iframe src=""  width="0" height="0" style="display:none;" name="tarframe"></iframe>
 </div>
 <div id="msg">
 </div>
 

index.js文件:
 

复制代码 代码示例:
$(function(){
 $("#upload_file").change(function(){
   $("#uploadFrom").submit();
 });
});
function stopSend(str){
 var im="<img src='upload/images/"+str+"'>";
 $("#msg").append(im);
}

upload.php文件:
 

复制代码 代码示例:
<?php
 $file=$_FILES['upfile'];
 $name=rand(0,500000).dechex(rand(0,10000)).".jpg";
 move_uploaded_file($file['tmp_name'],"upload/images/".$name);
//调用iframe父窗口的js 函数
 echo "<script>parent.stopSend('$name')</script>";
?>

方法三,原生态ajax文件上传
 

复制代码 代码示例:
<!DOCTYPE html>
<html>
<head>
    <title>Html5 Ajax 上传文件</title>
    <meta charset="utf-8">
<script type="text/javascript">
    var xhr;
    function createXMLHttpRequest()
    {
        if(window.ActiveXObject)
        {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if(window.XMLHttpRequest)
        {
            xhr = new XMLHttpRequest();
        }
    }
    function UpladFile()
    {
        var fileObj = document.getElementById("file").files[0];
        var FileController = 'upload.php';
        var form = new FormData();
        form.append("myfile", fileObj);
        createXMLHttpRequest();
        xhr.onreadystatechange = handleStateChange;
        xhr.open("post", FileController, true);
        xhr.send(form);
    }
    function handleStateChange()
    {
        if(xhr.readyState == 4)
        {
            if (xhr.status == 200 || xhr.status == 0)
            {
var result = xhr.responseText;
var json = eval("(" + result + ")");
alert('图片链接:n'+json.file);
            }
        }
    }
</script>
<style>
    .txt{ height:28px; border:1px solid #cdcdcd; width:670px;}
    .mybtn{ background-color:#FFF; line-height:14px;vertical-align:middle;border:1px solid #CDCDCD;height:30px; width:70px;}
    .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px }
</style>
</head>
<body>
<div class="form-group">
    <label class="control-label">图片</label>
    <br/>
    <input type='text' name='textfield' id='textfield' class='txt' />
    <span onclick="file.click()"  class="mybtn">浏览...</span>
    <input type="file" name="file" class="file" id="file" size="28" onchange="document.getElementById('textfield').value=this.value" />
    <span onclick="UpladFile()" class="mybtn">上传</span>
</div>
</body>
</html>

php代码:
 

复制代码 代码示例:
<?php
if(isset($_FILES["myfile"]))
{
$ret = array();
$uploadDir = 'images'.DIRECTORY_SEPARATOR.date("Ymd").DIRECTORY_SEPARATOR;
$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.$uploadDir;
file_exists($dir) || (mkdir($dir,0777,true) && chmod($dir,0777));
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = time().uniqid().'.'.pathinfo($_FILES["myfile"]["name"])['extension'];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$dir.$fileName);
$ret['file'] = DIRECTORY_SEPARATOR.$uploadDir.$fileName;
}
echo json_encode($ret);
}
?>