为什么图片文件在laravel中上传网址会给我404错误?

时间:2015-07-28 14:35:37

标签: php laravel model-view-controller laravel-5

我已经构建了一个简单的后端结构,其中包含创建,编辑,更新,视图,就像通常使用mvc和laravel一样。我正在使用的套餐是:

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "illuminate/html": "5.*",
        "codesleeve/laravel-stapler": "dev-master",
        "intervention/image": "^2.3",
        "dingo/api": "0.9.*"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1",
        "laracasts/generators": "^1.1",
        "way/generators": "~3.0"
    },

在向表单添加数据和更新时,它正在工作。数据结构如下:

"id": 1,
"name": "new offer",
"address": "test address",
"description": "test",
"offer_headline": "ccdd",
"offer_subheader": "hhhghhg",
"offer_terms": "test",
"map_location": "14,57",
"image": "/home/vagrant/projects/scoff/scoff-api/storage/app/uploads/2015-07-28-14:16:10-Screen Shot 2014-09-11 at 10.26.15.png",
"phone_number": "**************",
"website": "www.****.uk",
"created_at": "2015-07-28 14:16:10",
"updated_at": "2015-07-28 14:16:10",
"is_featured": false

我的控制器使用存储方法以非常简单的方式设置,如下所示。我的图像上传是通过laravel文件系统中的Store处理的,我使用图像干预来调整图像大小。正如您所见,图像被保存到数据库中,并且数据库中的URL是这样的:/home/vagrant/projects/scoff/scoff-api/storage/app/uploads/问题是当我到我的查找器查找文件时,它不在那里或者它没有被移动。我的控制器如下:

我已将相关部分留在此

<?php

namespace App\Http\Controllers;

use App\Offer;
use Validator;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use App\Http\Controllers\OfferTransformer;
use Redirect;
use Image;
use DB;
use Request;
use Storage;
use File;

class OffersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */


    /**
    * Return all api methods here
    **/
    public function apiIndex()
    {
        //
        $this->middleware('auth');
        return Offer::all();
    }

    public function apiShow($id)
    {
        $offer = Offer::findOrFail($id);
        return $this->response->array($offer->toArray());
    }



    public function index()
    {
        $this->middleware('auth');
        $offers = Offer::all();
        return view('offers.index', compact('offers'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */

    public function store(Offer $offer)
    {

        $data = Input::except('image');
        $validation = Validator::make($data, Offer::$rules);


        if ($validation->fails()) {
            return redirect('offers')->with('message', $validation->errors());
        } else {
            $file = Input::file('image');

            $filename = date('Y-m-d-H:i:s')."-".$file->getClientOriginalName();
            Image::make($file->getRealPath())->resize(600, 600)->save(storage_path('app/uploads/').$filename);

            // //$file = $file->move(public_path().'/images/offers/', time() . '-' . $file->getClientOriginalName());
            // // GET THE FILE EXTENSION
            $data['image'] = storage_path('app/uploads/').$filename;

            Offer::create( $data );
            return redirect('offers')->with('message', 'Offer added!');
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
        //dd($offer->exists);
        $offer = Offer::findOrFail($id);
        return view('offers.show', compact('offer'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit(Offer $offer, $id)
    {
        //
        $this->middleware('auth');
        $offer = Offer::findOrFail($id);
        return view('offers.edit', compact('offer'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Offer $offer, $id)
    {

        $offer = Offer::findOrFail($id);
        $input = array_except(Input::all(), array('_token','_method','image') );
        $file = Input::file('image');

        $filename = date('Y-m-d-H:i:s')."-".$file->getClientOriginalName();
        Image::make($file->getRealPath())->resize(600, 600)->save(public_path().'/images/offers/'.$filename);

        // //$file = $file->move(public_path().'/images/offers/', time() . '-' . $file->getClientOriginalName());
        // // GET THE FILE EXTENSION
        $input['image'] = public_path().'/images/offers/'.$filename;

        $offer->update($input);

        return Redirect::route('offers.show',$offer->id)->with('message', 'Offer updated.');
    }

}

谁能明白为什么会这样?是不是被搬到了正确的地方?

1 个答案:

答案 0 :(得分:0)

每条评论再次更新。

看起来您正在将文件保存到通常不公开的存储区域。尝试将storage_path更改为public_path。然后,您可以获取相对路径并将其存储在数据库中。

$relativePath = 'app/uploads/'.sanitize_file($filename);
Image::make($file->getRealPath())
  ->resize(600, 600)
  ->save(public_path().$relativePath);

$data['image'] = '/'.$relativePath;

您需要chmod 755chmod 775上传文件夹以允许服务器在那里保存文件,这通常是一个坏主意,但人们会这样做。

我通常使用云存储将图像保存到S3,然后从CloudFront提供。因此,我不能100%确定我会在同一个Web服务器上为他们提供服务。

我忘了str_slug也剥离了.。我使用这个辅助函数来清理文件。

if (!function_exists('sanitize_file')) {
    function sanitize_file($string, $force_lowercase = true, $anal = false)
    {
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", 
                       "(", ")", "_", "=", "+", "[", "{", "]", "}", "\\",
                       "|", ";", ":", "\"", "'", "&#8216;", "&#8217;",
                       "&#8220;", "&#8221;", "&#8211;", "&#8212;",
                       "—", "–", ",", "<", ">", "/", "?");
        $clean = trim(str_replace($strip, "", strip_tags($string)));
        $clean = preg_replace('/\s+/', "-", $clean);
        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean;
        return ($force_lowercase) ?
            (function_exists('mb_strtolower')) ?
                mb_strtolower($clean, 'UTF-8') :
                strtolower($clean) :
            $clean;
    }
}