2012-06-20

處理 PHP 上傳檔案

共用程式如下:
class Photo {

  public static $TABLE = 'bx_photo';
  public static $FIELDS = array(
  array('uuid','string'),
  array('name','name'),
  array('mime','mime'));

  public $id;
  public $uuid;
  public $name;
  public $mime;
  // transient
  public $tmp_name;

  public static function create($array) {
    // 將 $_FILE 裡的資訊讀入
    $p = new Photo();
    $p->mime = $array['type'];
    $p->name = $array['name'];
    $p->uuid = md5(uniqid());
    $p->tmp_name = $array['tmp_name'];
    return $p;
  }

  /*
   * 存檔:先存圖片檔到 FileSystem,再存到資料庫
  public static function sync($obj) {
    try {

      // 檢查 FileSystem 目錄
      if (!is_dir(BaseConfig::$PHOTO_PATH)) {
        mkdir(BaseConfig::$PHOTO_PATH);
      }

      // 存檔路徑
      $newPath = BaseConfig::$PHOTO_PATH.$obj->uuid;

      // 存檔
      if (move_uploaded_file($obj->tmp_name, $newPath)) {
        // 存檔成功
        // 更新到資料庫
        $con = Base::get();
        $con->beginTransaction();
        if (isset($obj->id)) {
          $st = $con->prepare(Base::createSql(self::$TABLE, self::$FIELDS, false));
        }
        else {
          $st = $con->prepare(Base::createSql(self::$TABLE, self::$FIELDS, true));
        }
        $st->execute(Base::setParams(self::$FIELDS, $obj));
        $con->commit();
      }
      else {
        // 存檔失敗
        echo "Can't move the uploaded file!";
      }
    }
    catch (Exception $e) {
      echo 'Database error: '.$e->getMessage();
      $con->rollback();
    }
  }
}
實際引用:
$photo = Photo::create($_FILES['upload']);
// 也許可以做些處理,然後再存檔
Photo::sync($photo);

沒有留言:

張貼留言