Libor Zapletal
Libor Zapletal

Reputation: 14102

Basic image upload in Joomla custom component

I am trying to add image upload function to my view where I am creating model. I tried many sample codes here but I can't get to full path to file. My code looks like this:

public function submit() {
    jimport ( 'joomla.filesystem.file' );
    // Check for request forgeries.
    JRequest::checkToken () or jexit ( JText::_ ( 'JINVALID_TOKEN' ) );

    // Initialise variables.
    $app = JFactory::getApplication ();
    $model = $this->getModel ( 'createaction' );

    // Get the data from the form POST
    $data = JRequest::getVar ( 'jform', array (), 'post', 'array' );

    echo $data['image'];   <-- here

    $createdItem = $model->createItem ( $data );
    if ($createdItem) {
        $redirect = JRoute::_ ( 'index.php?option=com_akcehned&view=actions', false );
        $this->setRedirect ( $redirect, "Akce byla vytvořena" );
    } else {
        echo "<h2>Omlouváme se, ale něco se stalo špatně</h2>";
    }

    return true;
}

Part of file input in xml:

    <field 
        name="image" 
        type="file" 
        description="COM_AKCEHNED_FORM_DESC_CREATEACTION_IMAGE" 
        label="COM_AKCEHNED_FORM_LBL_CREATEACTION_IMAGE" 
        size="10" 
        accept="image/*" />

Where I tried to echo file file input I get just name (image_name.jpg and so) but I need fullpath right? I saw examples with ['tmp_name'] but It's not working for me. I tried code like this:

$jinput = $app->input;
$files = $jinput->files->get('jform');
$file = $files['image'];
echo $file;
echo $file['tmp_name'];

But it's not working for me either. I just get empty values. Can someone give me working block of code where I get data from other inputs and fullpath to file for upload? It's for joomla 2.5, Thanks

Upvotes: 2

Views: 3986

Answers (2)

Laoneo
Laoneo

Reputation: 1566

Did you try DPAttachments, it takes only three lines of code to integrate attachment support into your component.

if (JLoader::import('components.com_dpattachments.libraries.dpattachments.core', JPATH_ADMINISTRATOR)) {
    echo DPAttachmentsCore::render('com_demo.item', $object->id);
}

Drag and drop and copy paste from your clipboard (no need to save the file to your hard disk) is supported. Perhaps you want to give it a try. If not here is a link to the Github repo how the upload function is implemented: https://github.com/Digital-Peak/DPAttachments/blob/master/com_dpattachments/admin/models/attachment.php#L50

[I'm the author of this component]

Upvotes: 1

WooDzu
WooDzu

Reputation: 4866

You need to make sure the the form tag contains enctype attribute and that it is set to "multipart/form-data" if your are going to upload files.

eg

<form action="" method="post" enctype="multipart/form-data">

Also see: What does enctype='multipart/form-data' mean?

Upvotes: 1

Related Questions