Проблема в том, что 1 файл не загружается и даже не сохраняется в базе данных и даже вставить URL не получается. Не понимаю, в чем проблема.
На практике этот модуль добавляет форму загрузки как через файл, так и через полный URL-адрес анимированного изображения в описании товара (при перейти к этапу модификации продукта). Очевидно, что когда вы загружаете гифку, ее нельзя конвертировать, иначе нет смысла загружать анимированные гифки, и тогда они будут отображаться статически. На данный момент модуль сохранит их в своей папке загрузок (внутри самого модуля).
[img]https://i.sstatic.net /iMws0sj8.png[/img]
colan_prod_gifs.php
if (!defined('_PS_VERSION_'))
{
exit;
}
class Colan_Prod_Gifs extends Module
{
public function __construct()
{
$this->name = 'colan_prod_gifs';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'Author';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Uploader GIF');
$this->description = $this->l('Carica GIF e visualizza nella galleria del prodotto.');
}
public function install()
{
return parent::install() && $this->installDb() && $this->registerHook('actionAdminControllerSetMedia') && $this->registerHook('displayAdminProductsExtra') && $this->registerHook('displayFooterProduct');
}
public function uninstall()
{
return parent::uninstall() && $this->uninstallDb();
}
public function installDb()
{
$sql = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'prod_gifs` (
`id_gif` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`id_product` INT UNSIGNED NOT NULL,
`gif_url` VARCHAR(255) NULL,
`gif_file` VARCHAR(255) NULL
) ENGINE=' . _MYSQL_ENGINE_;
return Db::getInstance()->execute($sql);
}
private function uninstallDb()
{
$sql = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prod_gifs`';
return Db::getInstance()->execute($sql);
}
public function hookActionAdminControllerSetMedia($params)
{
if ($this
->context
->controller->controller_name === 'AdminProducts')
{
// $this->context->controller->addJS($this->_path . 'views/js/admin.js');
// $this->context->controller->addCSS($this->_path . 'views/css/admin.css');
}
}
public function hookDisplayAdminProductsExtra($params)
{
$id_product = (int)$params['id_product'];
$query = 'SELECT * FROM `' . _DB_PREFIX_ . 'prod_gifs` WHERE id_product = ' . $id_product;
file_put_contents(__DIR__ . "/log.txt", "hookDisplayAdminProductsExtra select: " . $query . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
$gifs = Db::getInstance()->executeS($query);
if (Tools::isSubmit('submitGif'))
{
$this->handleGifUpload($id_product);
}
$this
->context
->smarty
->assign(['gifs' => $gifs, 'id_product' => $id_product, 'module_dir' => _MODULE_DIR_ . $this->name . '/uploads/', ]);
return $this->display(__FILE__, 'views/templates/admin/product_gifs.tpl');
}
private function handleGifUpload($id_product)
{
file_put_contents(__DIR__ . "/log.txt", "handleGifUpload id product " . $id_product . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
file_put_contents(__DIR__ . "/log.txt", "handleGifUpload FILES " . json_encode($_FILES) . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
if (isset($_FILES['gif_file']) && $_FILES['gif_file']['error'] === UPLOAD_ERR_OK)
{
$upload_dir = _PS_MODULE_DIR_ . $this->name . '/uploads/';
if (!is_dir($upload_dir))
{
mkdir($upload_dir, 0755, true);
}
// Sanitize the file name
$file_name = uniqid() . '_' . basename($_FILES['gif_file']['name']);
$file_path = $upload_dir . $file_name;
// Move the uploaded file
if (move_uploaded_file($_FILES['gif_file']['tmp_name'], $file_path))
{
// Save the file details in the database
Db::getInstance()->insert('prod_gifs', ['id_product' => (int)$id_product, 'gif_file' => $file_name, 'gif_url' => null, // Leave URL null if file is uploaded
]);
return true;
}
else
{
file_put_contents(__DIR__ . "/log.txt", "handleGifUpload upload gif errore urante il caricamento del file" . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
//$this->context->controller->errors[] = $this->l('Failed to upload the GIF file.');
return false;
}
}
elseif (Tools::getValue('gif_url'))
{
// Handle URL instead of file upload
$gif_url = Tools::getValue('gif_url');
Db::getInstance()->insert('prod_gifs', ['id_product' => (int)$id_product, 'gif_file' => null, // Leave file null if URL is provided
'gif_url' => pSQL($gif_url) , ]);
return true;
}
$this
->context
->controller
->errors[] = $this->l('No file or URL provided for GIF upload.');
return false;
}
public function hookDisplayFooterProduct($params)
{
$id_product = (int)Tools::getValue('id_product');
$gifs = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'prod_gifs` WHERE id_product = ' . $id_product);
$this
->context
->smarty
->assign(['gifs' => $gifs]);
return $this->display(__FILE__, 'views/templates/front/display_gifs.tpl');
}
}
display_gifs.tpl:
{l s='GIF Gallery' mod='colan_prod_gifs'}
{if $gifs}{foreach from=$gifs item=gif}
{/foreach}
{else}
{l s='Nessuna gif per il prodotto selezionato.' mod='colan_prod_gifs'}
{/if}
product_gifs.tpl:
{l s='GIF Gallery' mod='colan_prod_gifs'}
{l s='Upload GIF File' mod='colan_prod_gifs'}
{l s='Or Enter GIF URL' mod='colan_prod_gifs'}
{l s='Save GIF' mod='colan_prod_gifs'}
- {foreach from=$gifs item=gif}
-
{/foreach}
Подробнее здесь: https://stackoverflow.com/questions/792 ... e-uploader
Мобильная версия