首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 整合 jQuery Uploadify 實現多圖片批量上傳完整教程

     編輯:PHP 相關知識

Uploadify 是基於 jQuery 的 Flash/AJAX 批量上傳插件(註:現代專案建議使用 HTML5 方案如 Uppy、Dropzone、FilePond)。本文記錄在 CodeIgniter 架構下整合 Uploadify 的完整步驟,含資料庫擴展、表單渲染、前端初始化、後端接收與縮圖生成,供維護舊專案參考。

一、資料庫擴展

-- dili_fieldtypes 表新增欄位類型
INSERT INTO dili_fieldtypes (k, V) VALUES ('image', '圖片上傳區域');

二、模型層擴展

1. Field_behavior.php 新增欄位定義

case 'image':
    $field = [
        'type' => 'VARCHAR',
        'constraint' => 255,
        'default' => ''
    ];
    break;

2. Form.php 新增渲染方法

function _image($field, $default) {
    // 實際 HTML 由視圖層控制,這裡返回空
    return '';
}

三、視圖層表單整合

<!-- content_form.php / category_content_form.php -->
<?php if ($v['type'] == 'image'): ?>
    <div id="uploadify-container">
        <input type="file" name="file_upload" id="file_upload" />
        <button type="button" id="btn-upload">上傳</button>
        <button type="button" id="btn-cancel">取消上傳</button>
        <input type="hidden" name="image_path" id="image_path" value="" />
        <input type="hidden" name="image_thumb" id="image_thumb" value="" />
    </div>
    <link rel="stylesheet" href="asset/js/uploadify/uploadify.css" />
    <script src="asset/js/uploadify/jquery.uploadify.min.js"></script>
    <script>
    $(function() {
        $('#file_upload').uploadify({
            'swf'      : 'asset/js/uploadify/uploadify.swf',
            'uploader' : 'photo/_savephoto_post',
            'buttonText' : '選擇圖片',
            'fileTypeDesc' : '圖片文件',
            'fileTypeExts' : '*.jpg;*.jpeg;*.png;*.gif',
            'multi'    : true,
            'auto'     : false,
            'onUploadSuccess' : function(file, data, response) {
                // data 為後端返回的圖片路徑
                $('#image_path').val(data);
                // 如需即時預覽可在此追加 img 標籤
            }
        });
        $('#btn-upload').click(function() {
            $('#file_upload').uploadify('upload', '*');
        });
        $('#btn-cancel').click(function() {
            $('#file_upload').uploadify('cancel', '*');
        });
    });
    </script>
<?php endif; ?>

四、後端控制器 photo.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Photo extends Front_Controller {
    public function __construct() {
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai');
    }

    // 獲取存儲路徑:attachments/年/月/
    private function _getFilePath() {
        $path = "attachments/" . date("Y") . "/";
        if (!is_dir($path)) mkdir($path, 0755, true);
        $path .= date("m") . "/";
        if (!is_dir($path)) mkdir($path, 0755, true);
        return $path;
    }

    // 生成縮圖(等比縮放)
    private function _creat_photothumbs($fileName, $setW) {
        $info = getimagesize($fileName);
        if (!$info) return false;

        switch ($info['mime']) {
            case 'image/jpeg': $src = imagecreatefromjpeg($fileName); break;
            case 'image/png':  $src = imagecreatefrompng($fileName);  break;
            case 'image/gif':  $src = imagecreatefromgif($fileName);  break;
            default: return false;
        }

        $w = $info[0]; $h = $info[1];
        $scale = $h / $w;
        $nw = $setW; $nh = $nw * $scale;

        $dst = imagecreatetruecolor($nw, $nh);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $nw, $nh, $w, $h);
        imagejpeg($dst, $fileName, 90); // 覆蓋原檔
        imagedestroy($src); imagedestroy($dst);
        return true;
    }

    // 上傳處理入口
    public function _savephoto_post() {
        $dest_dir = $this->_getFilePath();

        if (!empty($_FILES)) {
            $file = $_FILES['Filedata']; // Uploadify 固定欄位名
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = date('YmdHis') . mt_rand(10000, 99999) . '.' . $ext;
            $dest = $dest_dir . $newName;

            if (move_uploaded_file($file['tmp_name'], $dest)) {
                // 寬度 > 600 生成等比縮圖
                $size = getimagesize($dest);
                if ($size[0] > 600) {
                    $this->_creat_photothumbs($dest, 600);
                }

                // 生成 170x150 縮略圖(CodeIgniter Image Library)
                $config = [
                    'image_library' => 'gd2',
                    'source_image'  => $dest,
                    'create_thumb'  => TRUE,
                    'maintain_ratio'=> TRUE,
                    'width'         => 170,
                    'height'        => 150,
                    'master_dim'    => 'width',
                    'thumb_marker'  => '_1',
                ];
                $this->load->library('image_lib', $config);
                $this->image_lib->resize();

                echo $dest; // 返回路徑給前端
            } else {
                echo 'UPLOAD_FAILED';
            }
        }
    }
}

五、安全與優化補充

  1. 檔案類型二次驗證:getimagesize() 確認 MIME,禁止上傳偽裝圖片的腳本。
  2. 儲存路徑不可直接訪問:將 attachments 置於 Web 根目錄外,或配置 Nginx internal 指令,透過 PHP 讀取輸出。
  3. 檔名隨機化:時間戳 + 隨機數 + 副檔名,防止覆蓋與遍歷猜測。
  4. 限制單檔/總大小:PHP upload_max_filesize、post_max_size、JS 端 fileSizeLimit 三重限制。
  5. 現代化替代:新專案請使用 Dropzone.js(純 HTML5、無 Flash 依賴、支援拖拽、進度條、預覽、分片上傳)。

六、總結

本文展示了 Uploadify 在 CodeIgniter 中的完整整合流程:資料庫擴展 → 模型定義 → 視圖渲染 + JS 初始化 → 後端接收 + 縮圖生成。雖 Uploadify 已停止維護(依賴 Flash),但理解其「前端隊列管理 + 後端單檔處理 + 異步回調」的架構模式,對掌握現代上傳組件(Uppy、Dropzone、FilePond)同樣有幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved