XF 2.1 Post file upload, how to map data:// folder to img src?

asprin

Active member
My file upload code is working fine, first hurdle passed. Now onto the second one......

I'm uploading it in the data:// directory using the following code:

PHP:
$uploads = $this->request->getFile('upload', false, false);
if($uploads)
{
    $uploads->requireImage();
    if (!$uploads->isValid($errors))
    {    
        return $this->error($errors[0]);
    }
 
    $dataDir = \XF::app()->config('externalDataPath');
    $datDir .= "://foo/bar/xyz.png";
    \XF\Util\File::copyFileToAbstractedPath($uploads->getTempFile(), $dataDir);
 
    // this is moving the file to <root>/data/foo/bar/xyz.png
}

Now when trying to use this path in template, what would be the correct approach of getting the fully qualified URL? For now I'm hardcoding it like this:

PHP:
// public controller

$fileid = 'xyz.png'; // this is pulled from database record
$path = 'data/foo/bar'; // this is the hardcoded stuff AND also I'm using relative path here
$fullpath = $path.'/'.$fileid;

$viewParms = [
    'url' => $fullpath
];

return $this->view('', 'asp_foobar', $viewParms);

Finally, inside the template asp_foobar:
HTML:
<img src="{$url}" alt="Logo" />

So this brings me to:
  1. Is this approach fine as far as best practices are concerned?
  2. If no, is there any helper function in XF that will get me the folder path without having to do some sort of hardcoding?
  3. Or at least something that will help me get to the data folder in the file system?
 
Solution
You can check out user avatars as good code reference for that. There's a handler in XF\Service that manages uploads and updates, and the remaining relevant code is in the User entity, something like getAbstractedAvatarPath for handling the file internally and getAvatarUrl for retrieving the user facing URL.
You can check out user avatars as good code reference for that. There's a handler in XF\Service that manages uploads and updates, and the remaining relevant code is in the User entity, something like getAbstractedAvatarPath for handling the file internally and getAvatarUrl for retrieving the user facing URL.
 
Solution
Thanks for pointing me in the right direction. The getAbstractedAvatarPath function helpful. This along with the base_url function in template seems to be doing the job.

HTML:
<img src="{{ base_url($entity.url) }}" alt="Some alternate text" />

<!--
$entity.url = data/myaddon/images/xyz.png
-->
 
Back
Top Bottom