电商店铺图片名称命名规则

  • 存放路径:商家id/店铺id/图片分类
 /**
     * [uploadImageLocal 将商品主图上传到本地服务器]
     * @return [type] [description]
     */
    private function uploadImageLocal($file, $partnerId, $storeId)
    {
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $file["file"]["name"]);
        $extension = end($temp);     // 获取文件后缀名
        if ((($file["file"]["type"] == "image/gif") || ($file["file"]["type"] == "image/jpeg") || ($file["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/pjpeg") || ($file["file"]["type"] == "image/x-png") || ($file["file"]["type"] == "image/png"))
            && ($_FILES["file"]["size"] <= 1024 * 1024 *2) && in_array($extension, $allowedExts))
        {  

            //api/Pandora/public/static/upload/shop/商家ID/店铺ID/main_image/11213141.png
            $path = ZK_APP_ROOT . 'public/static/upload/shop/' . $partnerId . '/' . $storeId . '/main_image/' . date('Ymd');
            $this->mkDirs($path);
            $fileName = $this->setFileName($storeId);
            $format = strrchr($file["file"]["name"], '.');

            move_uploaded_file($file["file"]["tmp_name"], $path . '/' . $fileName . $format);
            // return $path.'/' . $fileName.$format;
            return '/static/upload/shop/' . $partnerId . '/' . $storeId . '/main_image/' . date('Ymd') . '/' . $fileName . $format;
        }
    }

 
    
  • 设置图片名称:
    • sprintf(‘%010d’, time() – strtotime(‘2020-02-01 00:00:00’)) 10位随机数不足10位,前面补0
    • sprintf(‘%03d’, $usec * 1000) 3位随机数不足3位前面补0
    • sprintf(‘%04d’, mt_rand(0, 9999)); 4位随机数,不足的补0

   /**
     * [setFileName 设置图片的名称]
     * $storeId  店铺id
     * 生成(从2020-02-01 00:00:00 到现在的秒数+微秒+四位随机)
     */
    private function setFileName($storeId){
        list($usec, $sec) = explode(" ", microtime());
        $tmp_name = sprintf('%010d', time() - strtotime('2020-02-01 00:00:00'))
            . sprintf('%03d', $usec * 1000)
            . sprintf('%04d', mt_rand(0, 9999));
        return $storeId . '_' . $tmp_name;
    }
  • 循环创建无限极目录
/**
     * [mkDirs 递归创建图片的存储目录]
     * @param  [type] $dir [description]
     * @return [type]      [description]
     */
    private function mkDirs($dir){
        if (!is_dir($dir)) {
            if (!$this->mkDirs(dirname($dir))) {
                return false;
            }
            if (!mkdir($dir, 0777)) {
                return false;
            }
        }
        return true;
    }

Leave a comment

您的邮箱地址不会被公开。 必填项已用 * 标注