I use the code for downloading an image from directort that is outside of webroot but it is not work.
Here's my controller code:
public function download() {
$this->autoRender = false;
$this->view = 'Media';
$type = explode('.',$this->params['pass'][1]);
// Download app/outside_webroot_dir/example.zip
$params = array(
'id' => $this->params['pass'][1],
'name' => $this->params['pass'][0],
'download' => true,
'extension' => $type[1],
'path' => APP . 'media' . DS .'DealMenu'. DS . $this->params['pass'][0]. DS . $this->params['pass'][1]
);
$this->set($params);
}
Related
PLease help me on how to upload image in the folder and the same time in the database with a random name.
There's an error: Call to a member function getName() on null.
Heres my code in controller
`public function actionInsert()
{
$destination = new DestinationModel();
$name=$this->request->getVar('name');
$place=$this->request->getVar('place');
$location=$this->request->getVar('location');
$category=$this->request->getVar('category');
$description=$this->request->getVar('description');
$latitude=$this->request->getVar('latitude');
$longitude=$this->request->getVar('longitude');
$image=$this->request->getFile('image');
$imageName = $image->getName();
$image->move('im/destination', $imageName);
if($place == 'Calapan City')
{
$place = 'Calapan';
}else if($category == 'Destination')
{
$category ='Destination';
}
$data = [
'name' => $name,
'place' => $place,
'location' => $location,
'category' => $category,
'image' => $place. '/'. $imageName,
'description' => $description,
'latitude' => $latitude,
'longitude' => $longitude
];
$destination->save($data);
return view('adding_place');
}`
When I upload it in HTML form it works fine. but when I want to upload files from the Laravel public directory it's not working.
My code in Controller:
function createFile($file, $parent_id = null)
{
$file = FileStorage::find($file)->first()->UniqueFileName;
$name = gettype($file) === 'object' ? $file->getClientOriginalName() : $file;
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => $name,
'parent' => $parent_id ? $parent_id : 'root'
]);
$content = gettype($file) === 'object' ? File::get($file) : Storage::get($file);
$mimeType = gettype($file) === 'object' ? File::mimeType($file) : Storage::mimeType($file);
$file = $this->drive->files->create($fileMetadata, [
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
]);
dd($file->id);
}
I'm trying to upload an image using the API. Even though, after running the first test, the database just stored the directory and not the file-name, worst part, it stored all directories that come before the one that is needed to store the image.
The code I'm using for the store is the following one:
public function store(Request $request)
{
$image = $request->file('image');
if($image == null){
$imagesDir = 'subjectImgs/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$fileDir = $images[array_rand($images)];
$path = $fileDir;
} else {
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
}
$subject = new Homework([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$subject->save();
return response()->json([
"code" => 200,
"message" => "Homework added successfully"
]);
}
I'm uploading from a mobile device, I believe this info is also important (?) Same issue when in the simulator.
You are saving $path into $subject->image that is equal to public_path() . '/uploads/images/store/';. You should add $file->getClientOriginalName() if you want the filename :
$subject = new Homework([
...
'image' => $path . $file->getClientOriginalName(),
...
]);
You are settings 'image' => $path, and before that $path = public_path() . '/uploads/images/store/'; which yields the expected results.
Now if you want to only save from a form input, you can use the following code:
$image = $request->file('image');
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
Where 'public' is the default public filesystem as described in the doc here: https://laravel.com/docs/7.x/filesystem#the-public-disk
I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));
I am attempting to create a custom image field within Magento CMS pages.
This is the steps I have taken,
Created an additional column with cms_page within the database called 'banner' - this is a varchar (255).
Amended "app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php" with the uploader code (see at bottom).
Amended "app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php" to add the new field called 'banner' of which is a field type of 'image'.
Deleted everything within "var/cache/" and "var/session/"
It's just simply not uploading/saving the filename within the database. To try and diagnose what's going on I added print_r($_FILES) just below saveAction() and it returned an empty array.
Am I missing a crucial step?
Here is the relevant code,
app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php -
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$data = $this->_filterPostData($data);
//init model and set data
$model = Mage::getModel('cms/page');
if(isset($data['banner']['delete']) && $data['banner']['delete']=='1'){
if(!empty($data['banner']['value'])){
$path = Mage::getBaseDir('media') . DS;
if(#unlink($path.$data['banner']['value'])){
$data['banner']='';
}
}
}
if(isset($_FILES['banner']['name']) && !empty($_FILES['banner']['name'])) {
try {
$uploader = new Varien_File_Uploader('banner');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
// setAllowRenameFiles(true) -> move your file in a folder the magento way
// setAllowRenameFiles(false) -> move your file directly in the $path folder
$uploader->setFilesDispersion(true);
$path = Mage::getBaseDir('media') . DS;
//$uploader->saveresized($path, $_FILES['nfile']['name'],100,72);
//$_tmp_nfilethumb = $uploader->getUploadedFileName();
$uploader->save($path, $_FILES['banner']['name']);
$_tmp_nfile = $uploader->getUploadedFileName();
//$data['nfilethumb'] = $_tmp_nfilethumb;
$data['banner'] = $_tmp_nfile;
}catch(Exception $e) {
}
}elseif(isset($data['banner']['value']) && !empty($data['banner']['value'])){
$data['banner']=$data['banner']['value'];
}
if ($id = $this->getRequest()->getParam('page_id')) {
$model->load($id);
}
$model->setData($data);
Mage::dispatchEvent('cms_page_prepare_save', array('page' => $model, 'request' => $this->getRequest()));
//validating
if (!$this->_validatePostData($data)) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current' => true));
return;
}
// try to save it
try {
// save the data
$model->save();
// display success message
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('cms')->__('The page has been saved.'));
// clear previously saved data from session
Mage::getSingleton('adminhtml/session')->setFormData(false);
// check if 'Save and Continue'
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current'=>true));
return;
}
// go to grid
$this->_redirect('*/*/');
return;
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
catch (Exception $e) {
$this->_getSession()->addException($e,
Mage::helper('cms')->__('An error occurred while saving the page.'));
}
$this->_getSession()->setFormData($data);
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id')));
return;
}
$this->_redirect('*/*/');
}
app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php -
protected function _prepareForm()
{
$model = Mage::registry('cms_page');
/*
* Checking if user have permissions to save information
*/
if ($this->_isAllowedAction('save')) {
$isElementDisabled = false;
} else {
$isElementDisabled = true;
}
$form = new Varien_Data_Form();
$form->setHtmlIdPrefix('page_');
$fieldset = $form->addFieldset('content_fieldset', array('legend'=>Mage::helper('cms')->__('Content'),'class'=>'fieldset-wide'));
$wysiwygConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig(
array('tab_id' => $this->getTabId())
);
$fieldset->addField('content_heading', 'text', array(
'name' => 'content_heading',
'label' => Mage::helper('cms')->__('Content Heading'),
'title' => Mage::helper('cms')->__('Content Heading'),
'disabled' => false,
));
$content999Field = $fieldset->addField('banner', 'image', array(
'name' => 'banner',
'label' => Mage::helper('cms')->__('Banner'),
'title' => Mage::helper('cms')->__('Banner'),
));
$contentField = $fieldset->addField('content', 'editor', array(
'name' => 'content',
'label' => Mage::helper('cms')->__('Layout 1'),
'title' => Mage::helper('cms')->__('Layout 1'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content2Field = $fieldset->addField('content2', 'editor', array(
'name' => 'content2',
'label' => Mage::helper('cms')->__('Layout 2'),
'title' => Mage::helper('cms')->__('Layout 2'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content3Field = $fieldset->addField('content3', 'editor', array(
'name' => 'content3',
'label' => Mage::helper('cms')->__('Content'),
'title' => Mage::helper('cms')->__('Content'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
// Setting custom renderer for content field to remove label column
//$renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset_element')
// ->setTemplate('cms/page/edit/form/renderer/content.phtml');
// $contentField->setRenderer($renderer);
$form->setValues($model->getData());
$this->setForm($form);
Mage::dispatchEvent('adminhtml_cms_page_edit_tab_content_prepare_form', array('form' => $form));
return parent::_prepareForm();
}
Try to add this line below $form->setValues($model->getData());:
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
I added,
'enctype' => 'multipart/form-data' within the Form.php and it fixed it.
class Mage_Adminhtml_Block_Cms_Page_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post', 'enctype' => 'multipart/form-data'));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}