DIV CSS 佈局教程網

jQuery 插件 Uploadify 實現多圖上傳(可動態添加上傳框)
編輯:關於JavaScript     

本文分享使用 uploadify 插件實現多圖上傳的具體代碼,支持動態添加上傳框,供大家參考。

 <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uploadify Test</title>
<script src="jquery2.js" type="text/javascript"></script>
<script src="jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadify.css">
<style type="text/css">
body { font: 13px Arial, Helvetica, Sans-serif; }
</style>
</head>
<body>
<h1>Uploadify Demo</h1>
<div class='upload'>
<form>
<div class='form_file'>
<div class='file'>
<input id="file_upload1" name="file_upload" type="file" multiple="true">
</div>
</div>
</form>
</div>
<a href="javascript:;" class="clickUpload"> 點擊 </a>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function () {
    var i = 2;
    $('.clickUpload').click(function () {
        var html = '';
        html += '<div class="file"><input id="file_upload' + i + '" name="file_upload" type="file" multiple="true"></div>';
        $('.form_file').append(html);
        $('#file_upload' + i).uploadify({
            'formData': {
                'timestamp': '<?php echo $timestamp;?>',
                'token': '<?php echo md5('unique_salt' . $timestamp);?>'
            },
            'swf': 'uploadify.swf',
            'uploader': 'uploadify.php',
            'width': '120',
            'fileTypeExts': '*.gif; *.jpg; *.png',
            'buttonText': '上傳圖片',
            'removeCompleted': false,
            'multi': true, // 允許多圖上傳
            'onUploadSuccess': function (file, data, response) {
                $('#' + file.id).find('.data').html(' 上傳完畢');
            }
        });
        i++;
    });
    $('#file_upload1').uploadify({
        'formData': {
            'timestamp': '<?php echo $timestamp;?>',
            'token': '<?php echo md5('unique_salt' . $timestamp);?>'
        },
        'swf': 'uploadify.swf',
        'uploader': 'uploadify.php',
        'width': '120',
        'fileTypeExts': '*.gif; *.jpg; *.png',
        'buttonText': '上傳圖片',
        'removeCompleted': false,
        'multi': true, // 允許多圖上傳
        'onUploadSuccess': function (file, data, response) {
            $('#' + file.id).find('.data').html(' 上傳完畢');
        }
    });
});
</script>
</body>
</html>

實現要點

首先是引入 jQuery、uploadify 的 JS 與 CSS 文件。頁面初始化時對首個文件輸入框調用 uploadify 方法進行初始化,關鍵參數包括:swf 指定 Flash 組件路徑、uploader 指定後台上傳處理地址、fileTypeExts 限制可選文件類型、multi:true 開啟多文件上傳。

為實現「動態添加上傳框」,在點擊按鈕時通過 jQuery 動態 append 一個新的 input[type=file],並以自增變量 i 生成唯一 id,隨即對新元素再次調用 uploadify 完成初始化。這樣每次點擊都能新增一個獨立的多圖上傳框,互不干擾。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved