我需要为Magento Blog Module(AW博客)中的帖子创建图片上传字段。 因此,每个帖子都需要包含一个图像。
我编辑了以下文件: /home/clients/websites/w_gale/public_html/gale/app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php
添加了这样的字段集:
$fieldset->addField('fileinputname', 'image', array(
'label' => Mage::helper('blog')->__('Upload image'),
'required' => false,
'name' => 'fileinputname',
'required' => true,
'style' => 'height:100px;border:2px solid #999;',
));
在这个文件的顶部,在正确的位置,我定义了这样的形式:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
在Blogcontroller.php中,我添加了以下代码,只是在if ($data = $this->getRequest()->getPost()) {
行后面
if(isset($_FILES['fileinputname']['name']) && (file_exists($_FILES['fileinputname']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('fileinputname');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['fileinputname']['name']);
$data['imageurl'] = $_FILES['fileinputname']['name'];
} catch(Exception $e) {
}
} else {
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
$data['imageurl'] = '';
else
unset($data['fileinputname']);
}
但是,上传不起作用。我究竟做错了什么? 我在数据库的相应字段中添加了一个特殊行。 我手动输入时,前端部分显示数据库值。
由于
答案 0 :(得分:2)
这个上传图片的数据助手的方法代码。您需要实现方法getBaseDir()
(它可以在您希望存储上传文件的位置返回目录)。
/**
* Upload image and return uploaded image file name or false
*
* @throws Mage_Core_Exception
* @param string $scope the request key for file
* @return bool|string
*/
public function uploadImage($scope)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addValidator('ImageSize', true, $this->_imageSize);
$adapter->addValidator('Size', true, $this->_maxFileSize);
if ($adapter->isUploaded($scope)) {
// validate image
if (!$adapter->isValid($scope)) {
Mage::throwException(Mage::helper('mycompany_mymodule')->__('Uploaded image is not valid'));
}
$upload = new Varien_File_Uploader($scope);
$upload->setAllowCreateFolders(true);
$upload->setAllowedExtensions(array('jpg', 'gif', 'png'));
$upload->setAllowRenameFiles(true);
$upload->setFilesDispersion(false);
if ($upload->save($this->getBaseDir())) {
return $upload->getUploadedFileName();
}
}
return false;
}
答案 1 :(得分:0)
您正在使用正确的代码。我通过使用正确的MYSQL数据类型解决了这个问题。当我将数据类型从'text'更改为'varchar(255)'时,它解决了问题
并确保添加以下代码:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
在/app/code/community/AW/Blog/Block/Manage/Blog/Edit/Form.php中 NOT:app / code / community / AW / Blog / Block / Manage / Blog / Edit / Tab / Form.php