首页 > 解决方案 > CakePHP 3.x 从 URL 访问图像

问题描述

CakePHP 版本:3.6 系统:Windows 10 WampServer 3.1.3 (Apache)

我无法从 url 访问图像,即如果我输入: http ://www.n.co.nz/img/someimage.png我得到一个 404 未找到。我绝对能够在 CakePHP 2.0 中做到这一点,但在 CakePHP 3.6 中却无法做到。

图像“someimage.png”存储在 project/webroot/img/someimage.png

我可以通过 url 直接访问 css 文件,即 http://n.co.nz/css/template_pages.css

使用 cakePHP 方式时,图像加载正常,即

<?= $this->Html->image('someimage.png'); ?>

有任何想法吗?这是 .htaccess 还是路由问题?我的 .htaccess 如下

源文件/.htaccess

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$    webroot/    [L]
   RewriteRule    (.*) webroot/$1    [L]
</IfModule>

Webroot/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

更新

作为对 Peshraw 的回应,这里是 config/app.php 文件中我的“App”数组的内容:

'App' => [
    'namespace' => 'App',
    'encoding' => env('APP_ENCODING', 'UTF-8'),
    'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
    'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
    'base' => false,
    'dir' => 'src',
    'webroot' => 'webroot',
    'wwwRoot' => WWW_ROOT,
    //'baseUrl' => env('SCRIPT_NAME'),
    'fullBaseUrl' => false,
    'imageBaseUrl' => 'img/',
    'cssBaseUrl' => 'css/',
    'jsBaseUrl' => 'js/',
    'paths' => [
        'plugins' => [ROOT . DS . 'plugins' . DS],
        'templates' => [APP . 'Template' . DS],
        'locales' => [APP . 'Locale' . DS],
    ], 
];

作为回应顶级戴夫

The HTML that cake is generating when inserting an image the cake way is:

<img src="/img/nad_home_logo.png" id="nad_top_logo" alt="">

标签: phphtmlmod-rewritecakephpcakephp-3.0

解决方案


@Peshraw H. Ahmed

Are you sure you don't have typo in filename?

Nope... I added png instead of jpg for the image. CakePHP was telling me the below when trying to load the image directly using the URL

Error: ImgController could not be found. Error: Create the class ImgController below in file: src\Controller\ImgController.php

This threw me off, I thought cake wasn't routing the image resource calls to the webroot/img folder. I guess it was scanning that folder, not finding the resource and then propagating to see if there's an imgController that knows what to do?

Thanks for the help!


推荐阅读