为什么我在 laravel 站点的图片上总是收到 404 错误?

Why do I keep getting a 404 error on images in laravel site?

我想知道是否有人知道我遇到的这个奇怪错误,我有一个简单的表单,上面有一个文件输入字段。当您上传图像时,它会将图像添加到表单对象并将其 post 发送到 post 以便我可以检索它,但这并不像我想的那样有效。索引方法显示 posts 与图像:

这里是 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>

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

这是包含我添加的图像的 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());

    }

}

我可以在这里创建一个 post 并更新一个 post 但由于某些原因,添加到 post 的图像根本没有显示。

我的路由文件很好,因为它是我首先想到的问题,除非它是:

// 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 src="{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" /><img src="/{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" />

通过使用绝对路径,您可以确保您的链接始终 "resolve" 从项目的根目录开始,而无需担心您是否在 /posts/ 内。

只需将 / 添加到您的图像 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 添加到源的前面,例如,如果您在 http://localhost.com/foo 的 URL 页面上,您的图像源将变为 http://localhost.com/foo/path/to/my/image.png。通过添加 /,您告诉浏览器图像位于您网站的根目录之外 http://localhost.com/path/to/my/image.png

我用了下面的语句

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

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

这对我有用