joomla文件上传之com_media组件修改上传重命名文件方法

初接触joomla修改编辑时遇到的问题,因为原来的代码是上传文件后用的是你上传的文件的名字也许是为了防止上传相同的文件。而且上传后需要手动下滑找到刚上传的文件很不方便,现在我需要把上传的图片按照时间戳命名将新上传的文件重新命名并且排在前面。

com_media组件文件路径administrator/components/com_media/controllers/file.php

原来部分代码

public function upload()
{
// Check for request forgeries 这里是上传校验是否是登陆用户
JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN'));
$params = JComponentHelper::getParams('com_media');

// Get some data from the request 这里是获取上传的文件信息
$files = $this->input->files->get('Filedata', array(), 'array');
$return = JFactory::getSession()->get('com_media.return_url');

//这里主要是获取你上传的路径或文件夹
$this->folder = $this->input->get('folder', '', 'path');

// Don't redirect to an external URL.
if (!JUri::isInternal($return))
{
$return = '';
}

// Set the redirect
if ($return)
{
$this->setRedirect($return . '&folder=' . $this->folder);
}
else
{
$this->setRedirect('index.php?option=com_media&folder=' . $this->folder);
}

// Authorize the user
if (!$this->authoriseUser('create'))
{
return false;
}

// If there are no files to upload - then bail
if (empty($files))
{
return false;
}

// Total length of post back data in bytes.
$contentLength = (int) $_SERVER['CONTENT_LENGTH'];

// Instantiate the media helper
$mediaHelper = new JHelperMedia;

// Maximum allowed size of post back data in MB.
$postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size'));

// Maximum allowed size of script execution in MB.
$memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit'));

// Check for the total size of post back data.
if (($postMaxSize > 0 && $contentLength > $postMaxSize)
|| ($memoryLimit != -1 && $contentLength > $memoryLimit))
{
JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_WARNUPLOADTOOLARGE'));

return false;
}

$uploadMaxSize = $params->get('upload_maxsize', 0) * 1024 * 1024;
$uploadMaxFileSize = $mediaHelper->toBytes(ini_get('upload_max_filesize'));

// Perform basic checks on file info before attempting anything
foreach ($files as &$file)
{

//主要代码在这里这里是取出你上传的每个文件的信息我们将要修改的就是这个地方
$file['name'] = JFile::makeSafe($file['name']);
$file['name'] = str_replace(' ', '-', $file['name']);

//注意这里的$file['name'] 是文件全名wenjian.jpg  如果你直接替换会不知道什么类型会报错误的
$file['filepath'] = JPath::clean(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_BASE, $this->folder, $file['name'])));

if (($file['error'] == 1)
|| ($uploadMaxSize > 0 && $file['size'] > $uploadMaxSize)
|| ($uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize))
{
// File size exceed either 'upload_max_filesize' or 'upload_maxsize'.
JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE'));

return false;
}

if (JFile::exists($file['filepath']))
{
// A file with this name already exists
JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_FILE_EXISTS'));

return false;
}

if (!isset($file['name']))
{
// No filename (after the name was cleaned by JFile::makeSafe)
$this->setRedirect('index.php', JText::_('COM_MEDIA_INVALID_REQUEST'), 'error');

return false;
}
}

// Set FTP credentials, if given
JClientHelper::setCredentialsFromRequest('ftp');
JPluginHelper::importPlugin('content');
$dispatcher = JEventDispatcher::getInstance();

foreach ($files as &$file)
{
// The request is valid
$err = null;

if (!MediaHelper::canUpload($file, $err))
{
// The file can't be uploaded

return false;
}

// Trigger the onContentBeforeSave event.
$object_file = new JObject($file);
$result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', &$object_file, true));

if (in_array(false, $result, true))
{
// There are some errors in the plugins
JError::raiseWarning(100, JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors)));

return false;
}

if (!JFile::upload($object_file->tmp_name, $object_file->filepath))
{
// Error in upload
JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'));

return false;
}

// Trigger the onContentAfterSave event.
$dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file, true));
$this->setMessage(JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($object_file->filepath, strlen(COM_MEDIA_BASE))));
}

return true;
}

 

主要修改的代码部分

$file['name'] = JFile::makeSafe($file['name']);
$file['name'] = str_replace(' ', '-', $file['name']);

//这里是取文件的扩展名(后缀名)
$hz = substr($file['name'], strrpos($file['name'], '.')+1);

//重新拼接保存的文件名这里我用时间戳命名
$file['name']=date("Y").date("m").date("d").date("H").date("i").date("s").rand(100, 999).".".$hz;
$file['filepath'] = JPath::clean(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_BASE, $this->folder, $file['name'])));

扩展延伸

主要的上传代码的方法是JFile::upload($object_file->tmp_name, $object_file->filepath)类

JFile类位置libraries/joomla/filesystem/file.php

代码简介

/**
* Moves an uploaded file to a destination folder
*
* @param string $src The name of the php (temporary) uploaded file
* @param string $dest The path (including filename) to move the uploaded file to
* @param boolean $use_streams True to use streams
* @param boolean $allow_unsafe Allow the upload of unsafe files
* @param boolean $safeFileOptions Options to JFilterInput::isSafeFile
*
* @return boolean True on success
*
* @since 11.1
*/
public static function upload($src, $dest, $use_streams = false, $allow_unsafe = false, $safeFileOptions = array())

$src 这个参数是上传的临时文件名是表单提交的时候在tem里生成的临时文件

$dest 这里是你要保存的位置路径文件名

joomla文件上传之com_media组件修改上传重命名文件方法-上流阁

END 如果有不了解可以留言给我

*文章为作者独立观点,不代表上流阁立场
本文由 江风成 授权 上流阁 发表,并经上流阁编辑。转载此文章须经作者同意,并请附上出处(上流阁)及本页链接。原文链接https://www.o6c.com/web/2017/06/20/1012.html
发表评论

坐等沙发
相关文章
thinkphp PHPExcel网页暂时无法连接连接ERR_INVALID_RESPONSE信息解决办法
thinkphp PHPExcel网页暂时无法连接连接…
thinkphp PHPExcel导入到数据库,插入空白数据的解决方案
thinkphp PHPExcel导入到数据库,插入空…
laravel接收get传值和接收post传值
laravel接收get传值和接收post传值
PHP CURL支持HTTP、HTTPS 请求亲测可用
PHP CURL支持HTTP、HTTPS 请求亲测可用
Laravel数据库操作的三种方式
Laravel数据库操作的三种方式
扫描二维码实现通知临时停车和挡住自己车的车主
扫描二维码实现通知临时停车和挡住自己…
javaweb开发程序员php开发,微信开发。接受定制开发

最新评论