【问题标题】:Why do I keep getting a 404 error on images in laravel site?为什么我在 laravel 站点中的图像上不断收到 404 错误?
【发布时间】:2015-04-25 06:28:11
【问题描述】:

我想知道是否有人知道我遇到了这个奇怪的错误,我有一个简单的表单,上面有一个文件输入字段。当您上传图像时,它会将图像添加到表单对象并将其发布到该帖子,以便我可以检索它,但这并不像我想的那样工作。 index 方法显示带有图片的帖子:

这里是create.blade.php:

{!! Form::model(new Boroughcc\Post, ['route' => ['posts.store'], 'files' => true]) !!}
        @include('posts/partials/_form', ['submit_text' => 'Create Post'])
    {!! Form::close() !!}

这里是部分:

<div class="form-group">
    {!! Form::label('title', 'Title:') !!}
    {!! Form::text('title') !!}
</div>
<div class="form-group">
    {!! Form::label('featured_image', 'Featured Image:') !!}
    {!! Form::file('featured_image') !!}
</div>
<div class="form-group">
    {!! Form::label('body', 'Post body:') !!}
    {!! Form::textarea('body', null, array('id'=>'','class'=>'sir-trevor')) !!}
</div>
<div class="form-group">
    {!! Form::submit($submit_text, ['class'=>'btn primary']) !!}
</div>

这一切看起来都很好,但它只是没有将图像添加到帖子本身的展示部分,本质上它只是没有找到图像,因为我在实际帖子页面本身的图像上收到 404 错误。

这是我添加的图片的 post.show 视图:

@extends('app')

@section('content')
<section style="clear: both;">
    <article class="letterbox" style="background-image:url({{ $post->featured_image }});"></article>
</section>
<section id="product-intro-name">
    <hgroup class="article-header">
        <h1>{!! $post->slug_column !!}</h1>
    </hgroup>
</section>
<article class="container" id="{!! $post->slug !!}">

    <section>
        <article class="post col-lg-6 col-md-6 col-sm-6">
            <img src="{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" />
            {!! $post->body !!}
        </article>
    </section>

</article>
@if (Auth::guest())
@else
    {!! link_to_route('posts.edit', 'Edit the post', array( $post->getSlug() ), array('class' => 'btn btn-info')) !!}
@endif

@stop

这是我的 PostsController 的完整版:

<?php namespace Boroughcc\Http\Controllers;

use Input;
use Redirect;
use Storage;
use SirTrevorJs;
use STConverter;
use Validator;
use Image;
use Boroughcc\Post;
use Boroughcc\Http\Controllers\Controller;
use Request;

class PostsController extends Controller {

    // public function __construct()
    // {
    //     $this->addTitleSegments(['Journal', 'Post']);
    // }


    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
        $this->middleware('auth');
        return view('posts.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        // image upload function

        $input = Input::all();
        $validation = Validator::make($input, Post::$rules);

        // Get the uploaded file object
        $img = Input::file('featured_image');

        // Generate the necessary file details
        $extension = pathinfo($img->getClientOriginalName(), PATHINFO_EXTENSION);
        $filename = date('Y-m-d-H:i:s') . '.' . $extension;
        $path = 'img/posts/';

        // Move the uploaded image to the specified path
        // using the generated specified filename
        $img->move($path, $filename);

        // Save the post to the database
        // using the path and filename use above
        //dd($input);
        $post = Post::create(array(
            'title' => Input::get('title'),
            'body' => Input::get('body'),
            'featured_image' => $path . $filename
        ));

        return Redirect::route('posts.index')->with('message', 'Post created');


        //Post::create( $input );

        // return Redirect::route('posts.index')->with('message', 'Post created');


    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @param  int  $slug_column
     * @return Response
     */
    public function show(Post $post)
    {
        //
        $post->find($post->slug);
        $img = Input::get('featured_image');

        if ( $post->slug !== null ) {
            return Redirect::route('posts.show', array('id' => $post->id, 'slug_column' => $post->slug), 301);
        }
        return view('posts.show', compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit(Post $post)
    {
        //
        $post->find($post->slug);
        $this->middleware('auth');
        return view('posts.edit', compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(Post $post)
    {
        //$post = $post->find($post->slug);
        $this->middleware('auth');
        // $input = array_except(Input::all(), '_method');
        //$input = Request::all();
        $input = Request::except('_method','_token');
        $post->update($input);

        return Redirect::route('posts.show', $post->getSlug() )->with('message', 'Post updated.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Post $post)
    {
        //
        $post->delete();
        return Redirect::route('posts.index')->with('message', 'Post deleted.');
        //dd($post->toArray());

    }

}

我可以在此处创建帖子并更新帖子,但由于某种原因,添加到帖子中的图像根本不显示。

我的路线文件很好,因为我认为这是问题的第一件事,除非它是:

// Route for upload images
Route::any("/sirtrevorjs/upload", array("uses" => "SirTrevorJsController@upload"));

// Route for tweets
Route::any("/sirtrevorjs/tweet", array("uses" => "SirTrevorJsController@tweet"));

/// Posts ////

Route::model('posts', 'Post');

Route::resource('posts', 'PostsController');

Route::match(array('PATCH'), "/posts", array(
      'uses' => 'PostsController@update',
      'as' => 'posts.update'
));

Route::bind('posts', function($value, $route) {
    return Post::whereId($value)->first();
});

Route::bind('posts', function($value, $route) {
    return Post::whereSlugColumn($value)->first();
});

Route::get('/', 'HomeController@index');

Route::get('/about', ['uses' => 'HomeController@about',
    'as' => 'about']
);

Route::get('/journal', ['uses' => 'HomeController@journal',
    'as' => 'journal']
);

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

我知道我会因此而自责,但我想不通。

【问题讨论】:

  • 能否展示以下之一:* 图片源(右键查看源并复制生成的img标签) * 开发者工具控制台报错
  • Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8000/posts/img/posts/2015-02-23-19:26:35.gif 当我查看它时,图像就在那里,当我在其中输入该网址时,它会显示图像
  • 我知道发生了什么事,出于某种原因,在节目视图中它在 /posts url 中的外观并添加 /posts/img/2015-02-23-19:26:35.gif 这反过来又给出了 /posts/img/posts/2015-02-23-19:26:35.gif 这不正确它的 '/posts/img/ 2015-02-23-19:26:35.gif'
  • 是的,但我想确认一下,所以我要求提供控制台日志。我会在我的回答中解释更多

标签: php laravel image-processing routing laravel-5


【解决方案1】:

尝试在图像源前面加上正斜杠 /
&lt;img src="{!! $post-&gt;featured_image !!}" alt="{!! $post-&gt;slug !!} image" /&gt;&lt;img src="/{!! $post-&gt;featured_image !!}" alt="{!! $post-&gt;slug !!} image" /&gt;

通过使用绝对路径,您可以确保您的链接始终从项目的根目录“解析”,而不必担心您是否在 /posts/ 内部。

【讨论】:

    【解决方案2】:

    只需将 / 添加到您的图像 src 路径,以便从应用程序的根目录中提取它,而不是相对于当前 URI

    <section>
        <article class="post col-lg-6 col-md-6 col-sm-6">
            <img src="/{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" />
            {!! $post->body !!}
        </article>
    </section>
    

    如果没有 /,浏览器会将当前 URI 预先添加到源中,例如,如果您在 URL 为 http://localhost.com/foo 的页面上,则您的图像源将变为 http://localhost.com/foo/path/to/my/image.png。通过添加/,您告诉浏览器该图像位于您网站的根目录之外http://localhost.com/path/to/my/image.png

    【讨论】:

      【解决方案3】:

      我使用了以下语句

      <img src="{{{ .$post->featured_image }}}" alt="{!! $post->slug !!} image" />
      

      我的图片在 public/images/ 文件夹中 然后我的 $post->featured_image 将返回 /images/imagename.png

      这对我有用

      【讨论】:

      • 确保您将所有图像文件都放入公开,因为它的资产
      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 2021-03-15
      • 2015-04-12
      • 2012-06-16
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多