1

I work on a custom Joomla module that would let users to upload profile images. I created a JForm and wanted to use the form field type "file" as below:

<field name="Photo" type="file" label="Profile photo" size="10" accept="image/*" />
<field
    name="MAX_FILE_SIZE"
    value="5242880"
    type="hidden"
/> 

The form looks good and I can browse any images from my computer and submit the form. However when I dump the posted fields, I can see that my photo field has a simple string with the name of the image, not even the path of it.

What I'd like to do is to grab that image, check if it is safe, upload it and put it into a specified Joomla folder under the images folder.

This sounds like a common use case, but I was not able to find any description explaining the whole chain. So any hints, links, explanation, code samles would be higly appreciated.

Thanks a lot, w.

1 Answer 1

1

After some more googling and debugging, I figured it out. The trick was that I'm using a JForm and the file field can be accessed slightly differently. First you need to access the fields tag and then the file field itself (see the bold line below):

The form xml:

<form>
    <fields name="main">
        <fieldset name="basic" addfieldpath="/modules/mod_gng_regguide/models/fields">
...
        <field name="photo" type="file" label="Profile photo"/>
        </fieldset>
    </fields>
</form>

and the code to upload the image:

public static function uploadPhoto(GNGLocation $loc) {

        $input = JFactory::getApplication()->input;
        **$file  = $input->files->get('main')["photo"];** 


        // Cleans the name of the file by removing weird characters
        $filename = JFile::makeSafe($file['name']); 

        $src  = $file['tmp_name'];
        $dest = JPATH_SITE . "/images/Guides/" . $loc->get('name') . "/" . $filename;

        if (JFile::upload($src, $dest)) 
        {
            // The file has successfully been uploaded :)
        } 
        else 
        {
            // Oh crap, something happened. Run!
        }

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.