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

Symfony2 整合 Upload 庫實作圖片上傳功能

     編輯:PHP 綜合知識

安裝 Upload 庫

composer require codeguy/upload

基礎上傳服務封裝

建立 ZM\AdminBundle\Controller\DefaultController 並實作 uploadPic() 方法:

namespace ZM\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;

class DefaultController extends Controller
{
    /**
     * 上傳圖片並以使用者 ID 命名
     * @param string $user_id 使用者 ID
     * @param string $str     表單 file 欄位 name
     * @param string $path    儲存相對路徑
     * @return string|bool    成功回傳檔名(含副檔名),失敗回傳 false
     */
    public function uploadPic($user_id, $str, $path)
    {
        $fs = new Filesystem();
        if (!$fs->exists($path)) {
            $fs->mkdir($path, 0700);
        }

        $storage = new \Upload\Storage\FileSystem($path);
        $file = new \Upload\File($str, $storage);

        if ($file->getName() !== '') {
            $file->setName($user_id); // 以 user_id 為檔名
            $file->addValidations(array(
                new \Upload\Validation\Mimetype(array('image/png','image/jpg','image/jpeg','image/gif')),
                new \Upload\Validation\Size('2M')
            ));

            try {
                $file->upload();
                return $file->getNameWithExtension();
            } catch (\Exception $e) {
                // 可記錄 $file->getErrors()
                return false;
            }
        }
        return false;
    }
}

控制器繼承並呼叫上傳

namespace ZM\ApiBundle\Controller;

use ZM\AdminBundle\Controller\DefaultController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ContactController extends BaseController
{
    public function uploadHeadAction()
    {
        $request = Request::createFromGlobals()->request;
        $user_id = $request->get('user_id');

        if (!isset($_FILES['head']) || $_FILES['head']['error'] !== UPLOAD_ERR_OK) {
            return new Response(json_encode([
                'flag' => 2,
                'content' => '未選擇圖片或上傳錯誤'
            ]), 200, ['Content-Type' => 'application/json']);
        }

        $conn = $this->getDoctrine()->getConnection();
        $data = $conn->fetchAssoc("SELECT id, head FROM contact WHERE id = ? LIMIT 1", [$user_id]);

        if (empty($data['id'])) {
            return new Response(json_encode([
                'flag' => 3,
                'content' => '使用者不存在'
            ]), 200, ['Content-Type' => 'application/json']);
        }

        $path = 'image/head/';
        $file_name = $this->uploadPic($user_id, 'head', $path);

        if ($file_name) {
            $conn->executeUpdate("UPDATE contact SET head = ? WHERE id = ?", [$path . $file_name, $user_id]);
            return new Response(json_encode([
                'flag' => 1,
                'content' => '上傳成功'
            ]), 200, ['Content-Type' => 'application/json']);
        }

        return new Response(json_encode([
            'flag' => 0,
            'content' => '上傳失敗'
        ]), 200, ['Content-Type' => 'application/json']);
    }
}

關鍵點總結

  • Upload 庫提供流暢介面:驗證、重命名、儲存一氣呵成。
  • 以使用者 ID 命名避免檔名衝突,副檔名保留原檔。
  • 儲存路徑寫入資料庫,前端直接引用 /image/head/{user_id}.jpg。
  • 生產環境建議:
     • 使用獨立儲存服務(如 AWS S3、阿里云 OSS)
     • 圖片處理交給 LiipImagineBundle 或 Intervention Image
     • 上傳目錄設定 open_basedir、禁用腳本執行權限
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved