简体   繁体   中英

Image Upload / Laravel stores image as a .tmp and not .img file

I created a Forum which should upload an image.

In my form i`ve

{{ Form::file('image') }}

This is a part of my controller:

public function store()
{
    $input = Input::all();

    $v = Validator::make($input, Post::$rules);

    if ($v->passes()) {

        $post = new Post;
        $post->title = Input::get('title');
        $post->body = Input::get('body');

        $post->image = Input::file('image'); // your file upload input field in the form should be named 'file'

        $destinationPath = 'uploads/'.str_random(8);
        $filename = $post->image->getClientOriginalName();
        $extension =$post->image->getClientOriginalExtension(); //if you need extension of the file
        $uploadSuccess = Input::file('image')->move($destinationPath, $filename);


        $post->m_keyw = Input::get('m_keyw');
        $post->m_desc = Input::get('m_desc');
        $post->slug = Str::slug(Input::get('title'));
        $post->user_id = Auth::user()->id;
        $post->save();

        return Redirect::route('posts.index');
    }

    return Redirect::back()->withErrors($v);
}    

But laravel stores the image as a .tmp file in my database.

The path in my database is then "/uploads/xxxxx.tmp"

Why does laravel stores the image as .tmp and not as .img ?

What do i wrong and why does laravel stores the image as a .tmp file ?

The problem is in this line

$post->image = Input::file('image');

You assign the .temp image file to your model instance and that's what is stored in the database.

You can do it this way.

$post = new Post;

$post->title = Input::get('title');

$post->body = Input::get('body');

$file = Input::file('image');

$filename = $file->getClientOriginalName();

$destinationPath = 'uploads/'.str_random(8);

// This will store only the filename. Update with full path if you like

$post->image = $filename; 

$uploadSuccess = $file->move($destinationPath, $filename);

I solved this problem by deleting the 'image' column in my $fillable variable. In Model Post.php

protected $table = "posts";

protected $fillable = [
    'title',
    'image', //delete if exists
    'content'
];

.tmp file is the file which you select from your local computer. So you need to assign correct path to your model to store it with correct URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM