0

I'm working in CakePHP 3.4.

I have an image outside img directory, in files directory under webroot

I have a files directory inside webroot along with css, img, js.

I tried using it like

$this->Html->image(WWW_ROOT . 'files' . DS . 'myimage.jpg')

which is creating path as

/var/www/html/myproject/webroot/files/myimage.jpg

But this is not showing image. Copying and pasting path in another tab is loading image perfectly. Also, moving image file to img directory and using $this->Html->image('myimage.jpg') is working fine.

Why it is not working ? Also, It is easy to build url for directories css, img and js like

// Outputs http://example.com/img/icon.png
$this->Url->image('icon.png', true);
OR
// Outputs /img/icon.png
$this->Url->image('icon.png');

which will result as

http://example.com/img/icon.png

I want to build url for files directory like

http://example.com/files/myfile.jpg
OR
// /files/myfile.jpg

How to build url for directories other than img, css and js.?

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

0

I'd doubt that using that path as a URL will work, as it's a filesystem path, and that's where the problem is. HtmlHelper::image() only supports URLs, relative as well as abolute ones (I guess the docs on this could be improved).

By default relative paths are expected to be relative to the /img/ folder. In your case you could pass a (web)root-relative path, like:

/files/myimage.jpg

If you want to generate an absolute URL, use the fullBase option:

$this->Html->image('/files/myimage.jpg', ['fullBase' => true])

See also

ndm
  • 59,784
  • 9
  • 71
  • 110
  • can't we create a method under `Html` helper like `$this->Html->file('myfile.jpg`)` which will load file `/webroot/file` directory. Also you are saying to generate absolute path using `$this->Html->image('/files/myimage.jpg')`, what if directory contain other file types like `pdf, mp3, etc`? In my application `files` directory is used to store different file types. – Anuj TBE Apr 17 '17 at 01:40
  • @AnujTBE Of course you could create an extended helper with a custom method that takes care of all your file handling needs, but that doesn't really have anything to do with your original question. If you need to handle other filetypes as well, then you'd do the same if you use other the existing helpers methods, you'd pass root-relative URLs. – ndm Apr 17 '17 at 16:20