jQuery+php ajax檔案上傳實現代碼

來源:互聯網
上載者:User

很多項目中需要用到即時上傳功能,比如,選擇本地圖片後,立即上傳並顯示映像。本文結合執行個體講解如何使用jQuery和PHP實現Ajax即時上傳檔案的功能,使用者只需選擇本地圖片確定後即實現上傳,並顯示上傳進度條,上傳完成後,顯示圖片資訊。

HTML

本樣本基於jQuery以及相當出色的jquery.form外掛程式,所以,先要載入jquery庫和form外掛程式。

 代碼如下 複製代碼

<script type="text/javascript" src="jquery.min.js"></script> 
<script type="text/javascript" src="jquery.form.js"></script> 


接著在頁面中加入如下代碼:

 代碼如下 複製代碼

<div class="btn"> 
     <span>添加附件</span> 
     <input id="fileupload" type="file" name="mypic"> 
</div> 
<div class="progress"> 
    <span class="bar"></span><span class="percent">0%</span > 
</div> 
<div class="files"></div> 
<div id="showimg"></div> 

我們在html中放置一個添加附件的按鈕元素.btn,以及進度條.progress,用於顯示檔案資訊的.files和顯示圖片的#showimg

可以看出,我們用於上傳檔案的html中並沒有出現form表單,而正常的上傳功能是要依賴form表單的。我們的form表單是動態插入的,這樣可以避免一個大表單中出現多個form。

CSS

我們使用css可以將傳統的瀏覽檔案的表單控制項美化成一個按鈕,這樣看起來是不是很酷。

 代碼如下 複製代碼

 

.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:#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} 

jQuery

首先定義各種變數,注意動態將表單元素form插入到上傳按鈕部位,並且form的屬性enctype必須設定為:multipart/form-data。然後當點擊“上傳附件”按鈕,選擇要上傳的檔案後,調用jquery.form外掛程式的ajaxSubmit方法,如下代碼說明。

 代碼如下 複製代碼

$(function () { 
    var bar = $('.bar'); 
    var percent = $('.percent'); 
    var showimg = $('#showimg'); 
    var progress = $(".progress"); 
    var files = $(".files"); 
    var btn = $(".btn span"); 
    $("#fileupload").wrap("<form id='myupload' action='action.php'  
    method='post' enctype='multipart/form-data'></form>"); 
    $("#fileupload").change(function(){ //選擇檔案 
        $("#myupload").ajaxSubmit({ 
            dataType:  'json', //資料格式為json 
            beforeSend: function() { //開始上傳 
                showimg.empty(); //清空顯示的圖片 
                progress.show(); //顯示進度條 
                var percentVal = '0%'; //開始進度為0% 
                bar.width(percentVal); //進度條的寬度 
                percent.html(percentVal); //顯示進度為0% 
                btn.html("上傳中..."); //上傳按鈕顯示上傳中 
            }, 
            uploadProgress: function(event, position, total, percentComplete) { 
                var percentVal = percentComplete + '%'; //獲得進度 
                bar.width(percentVal); //上傳進度條寬度變寬 
                percent.html(percentVal); //顯示上傳進度百分比 
            }, 
            success: function(data) { //成功 
                //獲得後台返回的json資料,顯示檔案名稱,大小,以及刪除按鈕 
                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); //返回失敗資訊 
            } 
        }); 
    }); 
    ... 
}); 

關於jquery.form外掛程式的更多資訊,請參閱form外掛程式官網:http://malsup.com/jquery/form/,官網中詳細介紹了form外掛程式的API和各種選項設定以及樣本。

接下來,檔案上傳完成,如果使用者想刪除上傳的檔案,可以寫個ajax post請求來完成刪除操作。

 代碼如下 複製代碼

$(function () { 
    ...接上面的代碼 
    $(".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); 
            } 
        }); 
    }); 
}); 

PHP

action.php中需要處理圖片上傳以及刪除圖片。圖片上傳時需要驗證格式和大小,然後通過move_uploaded_file()方法上傳圖片,最後返回json格式的資料。刪除圖片時使用unlink()即可完成刪除操作。

 代碼如下 複製代碼

$action = $_GET['act']; 
if($action=='delimg'){ //刪除圖片 
    $filename = $_POST['imagename']; 
    if(!empty($filename)){ 
        unlink('files/'.$filename); 
        echo '1'; 
    }else{ 
        echo '刪除失敗.'; 
    } 
}else{ //上傳圖片 
    $picname = $_FILES['mypic']['name']; 
    $picsize = $_FILES['mypic']['size']; 
    if ($picname != "") { 
        if ($picsize > 512000) { //限制上傳大小 
            echo '圖片大小不能超過500k'; 
            exit; 
        } 
        $type = strstr($picname, '.'); //限制上傳格式 
        if ($type != ".gif" && $type != ".jpg") { 
            echo '圖片格式不對!'; 
            exit; 
        } 
        $rand = rand(100, 999); 
        $pics = date("YmdHis") . $rand . $type; //命名圖片名稱 
        //上傳路徑 
        $pic_path = "files/". $pics; 
        move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path); 
    } 
    $size = round($picsize/1024,2); //轉換成kb 
    $arr = array( 
        'name'=>$picname, 
        'pic'=>$pics, 
        'size'=>$size 
    ); 
    echo json_encode($arr); //輸出json資料 


本文藉助了jquery form外掛程式來完成單檔案上傳功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.