I have been searching this for quite a while but couldn't find a solution to match my need. I am developing a module for Joomla 2.5 . I need functionality to allow users to upload images/any file type from the backend in module configuration.
Question : How can I add field for file upload in joomla module.
Thanks!
Just a sample from the joomla docs:
<?php
//Retrieve file details from uploaded file, sent from upload form
$file = JRequest::getVar('file_upload', null, 'files', 'array');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
//First check if the file has the right extension, we need jpg only
if ( strtolower(JFile::getExt($filename) ) == 'jpg') {
if ( JFile::upload($src, $dest) ) {
header("Location: http://".$_SERVER["HTTP_HOST"]."/administrator"); Redirect to a page of your choice
} else {
echo "error !"; //Redirect and throw an error message
}
} else {
echo "Wrong extension !"; //Redirect and notify user file is not right extension
}
?>
For more detailed information and full example(s): http://docs.joomla.org/How_to_use_the_filesystem_package
Keep in mind that your HTML form must include
enctype="multipart/form-data"
otherwise you will not get any result with the joomla function!
Related
I can't figure out how to get a database file attachment, to be downloaded with is real file name.
My model have many file attachements (many attachOne) and there is no problem to get link to them with
{{ model.myfile.filename }}
What I want to do is to get those files downloaded with their real file name.
I try to define an ajax event handler in my layout like so :
function onDonwload()
{
$path = post('path');
$name = post('name');
// Storage::exists('uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf'); => OK
// Storage::exists($path); =>OK
$path = storage_path().'/app/'. $path;
return Response::download( $path, $name);
}
and
<button data-request="onDonwload"
data-request-data="path: 'uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf', name: 'my real name">
Download
</button>
No missing file error, but get the browser to freeze with an alert that say "A webpage slow down your browser, what do you want to do?".
Did I miss an important point?
You should add separate page for downloading files, Ajax can not help you to download file ( may be it can but process is little complex and long)
create page with /file-download/:id here you can specify any url wit param :id and give it name file-download you can give any name you like for demo i used this name.
In that Page Html section will be Blank and in Page's code section add this code. here you can also check additional security check like user is logged in or not file is of related user or not. for now i am just checking file is related to particular Modal or not.
function onStart() {
$fileId = $this->param('id');
$file = \System\Models\File::find($fileId);
// for security please check attachment_type == your model with namespace
// only then lat use download file other wise user can download all the files by just passing id
if($file && $file->attachment_type == 'Backend\Models\User') { // here add your relation model name space for comparison
$file->output('attachment');
}
else {
echo "Unauthorised.";
}
exit();
}
Generating links, please replace page name with page you created.
<a href="{{ 'file-download'|page({'id': model.myfile.id}) }}" >{{ model.myfile.filename }}</a>
Now, when you click on link file should be downloaded with its original name, and for invalid file id it should show message Unauthorised..
if any doubts please comment.
I have laravel5.4 application.I want to remove unused images/files from my upload folder which is not available in my database.
For example :
I have 50 images in my upload folder for user profile but some of the image not use for any user.i think he removed or update his image from frontend.
Yes i know we need to code to remove file when user update or remove profile picture at a time also delete from upload folder.but my app run from many time and i want to remove unused file using script not manually beacause i have lot's of files so it's hard to check and remove file manually.anyone can you please help me for create any function for remove file from folder.
Sorry for my bad English.
I use something like this in my AdminController to remove images by clicking on a button.
Maybe you need to change the path or extensions
public function deleteUnusedImages()
{
$file_types = [
'gif',
'jpg',
'jpeg',
'png'
];
$directory = public_path();
$files = File::allFiles($directory);
foreach ($files as $file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $file_types)) {
if(DB::table('users')->where('votes', '=', $file)->count())
continue; // continue if the picture is in use
echo 'removed' . basename($file)."<br />";
unlink($file); // delete if picture isn't in use
}
}
}
I'm working on a Joomla! 2.5/3.x editor-xtd button and I have a problem loading a layout from file on button click.
I have tried this method:
$link = 'plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;
$button = new JObject;
$button->modal = true;
$button->class = 'btn';
$button->link = $link;
$button->text = 'Insert something';
$button->name = 'myplugin';
$button->options = "{handler: 'iframe', size: {x: 500, y: 300}}";
... but the full generated link in admin looks like http://my.local.host/mywebsite/administrator/plugins/editor-xtd/link-etc.. and it doesn't work. I also have tried including JURI::base in my $link, but the administrator path is still loaded.
I'm new in plugin dev with Joomla! and I have search a lot but no solution found.
** I also tried a link like this index.php?folder=plugins.editors-xtd.myplugin&file=myplugin.layout.php&name=$name but still nothing.
Is there a workout for this or I'll have to create&use a javascript function to run on button click?
Solution
Modify link variable like this (if application is admin):
$link = '../plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;
... and delete button options (this means that file contents will be loaded via ajax inside modal)
Further more, in myplugin.layout.php we can add a little security check and we can import Joomla! framework library and defines so that we can make use of Joomla! framework in our file (things like language load for eg.)
This is my actual header of file:
<?php
// No direct access
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if( ! IS_AJAX) die;
// Include J!Framework for later use
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../../..'));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE.DS.'includes'.DS.'defines.php');
require_once ( JPATH_BASE.DS.'includes'.DS.'framework.php');
//more magic goes here...
Unfortunately there is a bit of a gotcha here in that the JED checker process requires that ALL php files start with defined('_JEXEC') or die; on the very first line of code so if you want to share it on extensions.joomla.org then you are stymied...
Back on the OP you can detect whether you are in the Admin or Site before generating the link:
$app = JFactory::getApplication();
// ...
if ($app->isAdmin()) {
$root = '../'; // Joomla expects a relative path, leave site folder "administrator"
} else {
$root = '';
}
$button->link = $root.'/plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;
Also, as you may already know the $button->name = 'myplugin'; needs to be the name of the icon from the Joomla icomoon set - you can see them here https://ma.tvtmarine.com/en/blog/112-joomla-icomoon-icons-directory
The name needs to be the icon name without the .icon- bit eg:
$button->name = 'warning-2';
code block doesn't seem to be working properly...sorry about the formatting
i want set profile image for customer and i upload image from my account tab and set tab separate for our custom module profile. when sent the image from .phtml then the array of $_FILES is empty so my question is that how set profile image for customer in magento my code is in my saveimageAction. so one they doing work on that?
print_r($_FILES);exit();
if(isset($_FILES['profileimage']['name']) && ($_FILES['profileimage']['tmp_name'] != NULL))
{
$uploader = new Varien_File_Uploader('file');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$path = Mage::getBaseDir('media') . DS ;
//$path= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
$path = $path ."supportportal/avatar";
$uploader->save($path, $_FILES['profileimage']['name']);
$simage = Mage::getModel('supportportal/profile');
$simage->setData('user_id',$getuserid);
$simage->setData('image', $userimage);
$simage->setData('created_date',date('d-m-Y H:i:s'));
$simage->setData('last_updated_date',date('d-m-Y H:i:s'));
$simage->setData('status',1);
$simage->save();
Mage::getSingleton('core/session')->addSuccess( $this->__('Image is Successfully Save!') );
Mage::app()->getResponse()->setRedirect(Mage::getUrl('supportportal/index/profile/'));
}else{
Mage::getSingleton('core/session')->addError( $this->__('Image Saving Error!') );
Mage::app()->getResponse()->setRedirect(Mage::getUrl('supportportal/index/profile/'));
}
Check the html out put and make sure the form "enctype" attribute has below given value
<form action="your_controller_action" method="post" enctype="multipart/form-data">
Recently google change image search and as a result most of the traffic click over view original image and it send them to direct image file.
I have changed my .htaccess and stop all hot linking and redirect to my homepage if they click over image file.
Recently I've also tried if it is possible to redirect to post or page where image is.
By the following code
<?php
require('../wp-blog-header.php');
$imageURL = strip_tags( $_GET['id'] );
if imageURL!== "") {
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment'AND post_parent > '0' AND guid = '$imageURL'";
$linkedImage = $wpdb-get_row($query);
$attachmentUrl = get_attachment_link($linkedImage->ID);
if($attachmentUrl !== "" && !is_numeric(stripos($attachmentUrl, "attachment_id=0"))) {
header("HTTP/1.1 302 Found");
header("Location: ". $attachmentUrl);
exit;
}
}
$newUrl = get_site_url() . "/image-not-found";
header("HTTP/1.0 404 Not Found");
header("Location: " . $newUrl);
exit;
?>
But it redirect to http://www.mydomain.com/?attachment_id=
id is nil or can't fetch the proper id
My website in Wordpress CMS version 3.5.1
can anyone help how to redirect to proper attachment page for .jpg file direct request.
Thanks in advance
Your code would only work if there was an ID parameter on the requested URL that would be an exact match with the image URL, for instance http://www.example.com/?id=http://www.example.com/uploads/Some-Image.jpg
Is this the case? Even so, you shouldn't use id since it's a reserved parameter for other things in WP. In your .htaccess, you should redirect http://www.example.com/uploads/Some-Image.jpg to, for example, http://www.example.com/?image_redirect=http://www.example.com/uploads/Some-Image.jpg. Then use $imageURL = $_GET['image_redirect'].
Other notes: strip_tags doesn't make a string safe to use as a SQL query. In WordPress, you have esc_sql($string) for that. Also, you should rather use if ( $imageUrl != '' ), not with !==. And there's an error on line 5, it should say $wpdb->get_row, you currently have a minus sign. I assume these are typos. And finally, you shouldn't use Location: header with a status code 404.