程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> AJAX無刷新上傳圖片

AJAX無刷新上傳圖片

編輯:關於PHP編程

    目錄結構如下:

    其中files文件夾中存放上傳來的圖片。

    index.html代碼如下:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.demo{width:620px; margin:30px auto}
.demo p{line-height:32px}
.btn{position: relative;overflow: hidden;margin-right: 4px;display:inline-block;*display:inline;padding:4px 10px 4px;font-size:14px;line-height:18px;*line-height:20px;color:#fff;text-align:center;vertical-align:middle;cursor:pointer;background-color:#5bb75b;border:1px solid #cccccc;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
.btn input {position: absolute;top: 0; right: 0;margin: 0;border: solid transparent;opacity: 0;filter:alpha(opacity=0); cursor: pointer;}
.progress { position:relative; margin-left:100px; margin-top:-24px; width:200px;padding: 1px; border-radius:3px; display:none}
.bar {background-color: green; display:block; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; height:20px; display:inline-block; top:3px; left:2%; color:#fff }
.files{height:22px; line-height:22px; margin:10px 0}
.delimg{margin-left:20px; color:#090; cursor:pointer}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
</head>

<body>
<!--<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'>-->
<p id="main">
<span class="demo">       
        <input id="fileupload" type="file" name="mypic">
        <span class="btn">上傳</span>
</span>
</p>
<!--</form>-->
<script type="text/javascript">
$(function () {
    var bar = $('.bar');
    var percent = $('.percent');
    var showimg = $('#showimg');
    var progress = $(".progress");
    var files = $(".files");
    var btn = $(".btn span");
    $("p").wrap("<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'></form>");
    $("#fileupload").change(function(){
        $("#myupload").ajaxSubmit({
            dataType:  'json',
            beforeSend: function() {
                showimg.empty();
                progress.show();
                var percentVal = '0%';
                bar.width(percentVal);
                percent.html(percentVal);
                btn.html("上傳中...");
            },
            uploadProgress: function(event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
                bar.width(percentVal);
                percent.html(percentVal);
            },
            success: function(data) {
                files.html("<b>"+data.name+"("+data.size+"k)</b> <span class='delimg' rel='"+data.pic+"'>刪除</span>");
                var img = "http://demo.helloweba.com/upload/files/"+data.pic;
                showimg.html("<img src='"+img+"'>");
                btn.html("添加附件");
            },
            error:function(xhr){
                btn.html("上傳失敗");
                bar.width('0')
                files.html(xhr.responseText);
            }
        });
    });
    
    $(".delimg").live('click',function(){
        var pic = $(this).attr("rel");
        $.post("action.php?act=delimg",{imagename:pic},function(msg){
            if(msg==1){
                files.html("刪除成功.");
                showimg.empty();
                progress.hide();
            }else{
                alert(msg);
            }
        });
    });
});
</script>
</body>
</html>

 

     jquery.form.js代碼如下:

"use strict"


 feature == $("<input type='file'/>").get(0).files !=== window.FormData !=== 

    
     (!'ajaxSubmit: skipping submit process - no element selected'  method, action, url, $form =  ( options == 'function'== .attr('method'= .attr('action'= ( action === 'string') ? $.trim(action) : ''= url || window.location.href || ''
        url = (url.match(/^([^#]+)/)||[])[1= $.extend(|| 'GET'/^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
    
     veto =.trigger('form-pre-serialize', ['ajaxSubmit: submit vetoed via form-pre-serialize trigger' 
     (options.beforeSerialize && options.beforeSerialize(, options) === 'ajaxSubmit: submit aborted via beforeSerialize callback'  traditional = ( traditional ==== elements = qx, a = ==
     (options.beforeSubmit && options.beforeSubmit(a, , options) === 'ajaxSubmit: submit aborted via beforeSubmit callback' 
    .trigger('form-submit-validate', [a, 'ajaxSubmit: submit vetoed via form-submit-validate trigger'  q == ( q ? (q + '&' + (options.type.toUpperCase() == 'GET'+= (options.url.indexOf('?') >= 0 ? '&' : '?') += ;  
= q; 
 callbacks =
     (!options.dataType && oldSuccess = options.success ||  fn = options.replaceTarget ? 'replaceWith' : 'html' = (data, status, xhr) { 
         context = options.context ||  ;    
         ( i=0, max=callbacks.length; i < max; i++||
     fileInputs = $('input:file:enabled[value]', ); 
     hasFileInputs = fileInputs.length > 0 mp = 'multipart/form-data' multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == fileAPI = feature.fileapi &&"fileAPI :" + shouldUseFrame = (hasFileInputs || multipart) && !
    
     (options.iframe !==  && (options.iframe ||
        
          ((hasFileInputs || multipart) &&
     ( k=0; k < elements.length; k++= 
    .trigger('form-submit-notify', [ 
     serialized = $.param(extraData).split('&' len = result = (i=0; i < len; i++= serialized[i].split('='0])] = decodeURIComponent(part[1
     formdata =  ( i=0; i < a.length; i++ serializedData = ( p =  s = $.extend('POST'
            s.xhr =  xhr ==  percent = 0 position = event.loaded || event.position; 
                         total == Math.ceil(position / total * 100=  beforeSend == =
     form = $form[0 useProp = !! ($(':input[name=submit],:input[id=submit]'
            
            alert('Error: Form elements must not have name or id of "submit".'
             (i=0; i < elements.length; i++='disabled', 'disabled'= $.extend(= s.context ||= 'jqFormIO' + (== $io.attr('name' (!'name'== $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />''absolute', top: '-1000px', left: '-1000px'= $io[0= { 
            aborted: 00'n/a' e = (status === 'timeout' ? 'timeout' : 'aborted''aborting upload... ' +.aborted = 1
                 { 
                        io.contentWindow.document.execCommand('Stop''src', s.iframeSrc); 
                xhr.error ="ajaxError"=
         (g && 0 === $.active++"ajaxStart""ajaxSend" (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === --
        sub == (n && != s.extraData ||= (sub.type == "image"+'.x'] =+'.y'] = CLIENT_TIMEOUT_ABORT = 1 SERVER_ABORT = 2 doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ?
         csrf_token = $('meta[name=csrf-token]').attr('content' csrf_param = $('meta[name=csrf-param]').attr('content' (csrf_param &&= s.extraData ||=
        
             t = $form.attr('target'), a = $form.attr('action'
            form.setAttribute('target' (!'method', 'POST' (a !='action'
             (! s.skipEncodingOverride && (!method || /post/'multipart/form-data''multipart/form-data'
            = setTimeout(() { timedOut = 
             state ='state = ' + (state && state.toLowerCase() == 'uninitialized'50'Server abort: ' , e, ' (', e.name, ')'=
             extraInputs = ( n 
                           ($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value''<input type="hidden" name="'+s.extraData[n].name+'">').attr('value'0'<input type="hidden" name="'+n+'">').attr('value'0 (!
                    $io.appendTo('body''onload''load', cb, 15
                form.setAttribute('action''target''target'10); 
 data, doc, domCheckCount = 50 (xhr.aborted ||='cannot access response document: '= (e === CLIENT_TIMEOUT_ABORT &&'timeout'  (e == SERVER_ABORT &&'server abort' (!doc || doc.location.href ==
                 (!'onload''load', cb,  status = 'success' 'timeout' isXml = s.dataType == 'xml' || doc.XMLDocument ||'isXml='+ (!isXml && window.opera && (doc.body ===  || ! (--
                        
                        log('requeing onLoad callback, DOM not available'250
                    
                    

                 docRoot = doc.body ?= docRoot ? docRoot.innerHTML : = doc.XMLDocument ?= 'xml'=  headers = {'content-type'
                = Number( docRoot.getAttribute('status') ) ||= docRoot.getAttribute('statusText') || dt = (s.dataType || '' scr = /(json|script|text)/ (scr ||
                     ta = doc.getElementsByTagName('textarea')[0=
                        xhr.status = Number( ta.getAttribute('status') ) ||= ta.getAttribute('statusText') || 
                         pre = doc.getElementsByTagName('pre')[0 b = doc.getElementsByTagName('body')[0= pre.textContent ? = b.textContent ?  (dt == 'xml' && !xhr.responseXML &&=== 'parsererror'= errMsg = (e ||'error caught: '= 'error'= errMsg = (e ||'upload aborted'=  (xhr.status) { 
                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'
             (status === 'success''success'"ajaxSuccess"  (errMsg ===="ajaxError""ajaxComplete" (g && ! --"ajaxStop"= 
            setTimeout( (!= 100 toXml = $.parseXML || (s, doc) { 
            =  ActiveXObject('Microsoft.XMLDOM'= 'false'= ( DOMParser()).parseFromString(s, 'text/xml' (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc :  parseJSON = $.parseJSON || 
             window['eval']('(' + s + ')' httpData = ( xhr, type, s ) { 

             ct = xhr.getResponseHeader('content-type') || ''= type === 'xml' || !type && ct.indexOf('xml') >= 0= xml ? (xml && data.documentElement.nodeName === 'parsererror''parsererror' (s &&= ( data === 'string' (type === 'json' || !type && ct.indexOf('json') >= 0=  (type === "script" || !type && ct.indexOf("javascript") >= 0= = options ||= options.delegation &&
     (!options.delegation && .length === 0 o = { s: .selector, c:  (!$.isReady &&'DOM not ready, queuing ajaxForm' 
        log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)' 'submit.form-plugin', 'click.form-plugin', 'submit.form-plugin', 'click.form-plugin',   'submit.form-plugin''click.form-plugin'

     options = (!e.isDefaultPrevented()) { 

     target = $el = (!($el.is(":submit,input:image"
         t = $el.closest(':submit' (t.length === 0= t[0 form = = (target.type == 'image' (e.offsetX !====  ( $.fn.offset == 'function' offset == e.pageX -= e.pageY -= e.pageX -= e.pageY -
    setTimeout(() { form.clk = form.clk_x = form.clk_y = ; }, 100
$.fn.ajaxFormUnbind =  .unbind('submit.form-plugin click.form-plugin'=  a = (.length === 0 form = [0 els = semantic ? form.getElementsByTagName('*' (!(i=0, max=els.length; i < max; i++== (! (semantic && form.clk && el.type == "image"
            (!el.disabled && form.clk ==+'.x', value: form.clk_x}, {name: n+'.y'= $.fieldValue(el,  (v && v.constructor ==(j=0, jmax=v.length; j < jmax; j++  (feature.fileapi && el.type == 'file' && ! files = (j=0; j < files.length; j++
                a.push({ name: n, value: ''  (v !==  &&  v != 'undefined' (!semantic &&
         $input = $(form.clk), input = $input[0= (n && !input.disabled && input.type == 'image'+'.x', value: form.clk_x}, {name: n+'.y'= 
     $.param(=  a =.each( n =  (! v = $.fieldValue( (v && v.constructor == ( i=0,max=v.length; i < max; i++  (v !==  &&  v != 'undefined'
    =  ( val=[], i=0, max=.length; i < max; i++ el =  v = (v ===  ||  v == 'undefined' || (v.constructor == Array && ! (v.constructor ===  n = el.name, t = el.type, tag = (successful ====  (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||== 'checkbox' || t == 'radio') && !el.checked ||== 'submit' || t == 'image') && el.form && el.form.clk != el ||== 'select' && el.selectedIndex == -1  (tag == 'select' index = (index < 0  a = [], ops = one = (t == 'select-one' max = (one ? index+1( i=(one ? index : 0); i < max; i++ op = v = (!v) { 
                    v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ?=  .each('input,select,textarea', = $.fn.clearInputs =  re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; 
     .each( t = .type, tag =  (re.test(t) || tag == 'textarea'.value = ''  (t == 'checkbox' || t == 'radio'.checked =   (tag == 'select'.selectedIndex = -1 
            
            
            
             ( (includeHidden ===  && /hidden/.test(t)) || includeHidden == 'string' && $(.value = ''=  .each(
        
         ( .reset == 'function' || ( .reset == 'object' && !=  (b ====  .each(.disabled = !=  (select ====  .each( t =  (t == 'checkbox' || t == 'radio'.checked =  (.tagName.toLowerCase() == 'option' $sel = $().parent('select' (select && $sel[0] && $sel[0].type == 'select-one'
                $sel.find('option').selected(.selected =
$.fn.ajaxSubmit.debug = 
 (! msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'' (window.console &&  (window.opera &&

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved