dongli564510 2015-02-23 19:49
浏览 36
已采纳

为什么我一直在laravel网站上的图像上出现404错误?

I wondered if anyone knew of this strange error I am having, I have a simple form that has a file input field on it. When you upload the image it adds the image to the form object and posts it to that post so I can retrieve it, but this is not working as I thought. The index method shows the posts with the image:

enter image description here

Here is the create.blade.php:

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

And here is the partial:

<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>

This is all seems fine but its just not adding the image to the show part of the post itself, in essence its just not finding the image as I am getting a 404 error on the image on the actual post page itself.

enter image description here

Here is the post.show view with the image I have added:

@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

Here is my PostsController in full:

<?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());

    }

}

I can create a post here and update a post but for some reason the image added to the post does not show up at all.

My routes file is fine as its the first thing I thought would be the issue unless it is:

// 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',
]);

I know I will kick myself with this but I cannot figure it out.

  • 写回答

3条回答 默认 最新

  • dprc88435 2015-02-23 20:07
    关注

    Try prepending the image source with a forward slash /
    <img src="{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" /> to <img src="/{!! $post->featured_image !!}" alt="{!! $post->slug !!} image" />

    By using absolute paths, you're making sure that your links will always "resolve" from the root of your project, without you having to worry if you're inside /posts/ or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?