【问题标题】:Image Upload / Laravel stores image as a .tmp and not .img file图片上传/Laravel 将图片存储为 .tmp 而不是 .img 文件
【发布时间】:2014-05-16 09:38:13
【问题描述】:

我创建了一个应该上传图片的论坛。

以我的形式,我已经

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

这是我的控制器的一部分:

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);
}    

但是 laravel 将图像作为 .tmp 文件存储在我的数据库中。

我的数据库中的路径是“/uploads/xxxxx.tmp”

为什么 laravel 将图片存储为 .tmp 而不是 .img ?

我做错了什么,为什么 laravel 将图像存储为 .tmp 文件?

【问题讨论】:

    标签: php mysql laravel frameworks


    【解决方案1】:

    问题出在这一行

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

    您将 .temp 图像文件分配给模型实例,这就是存储在数据库中的内容。

    你可以这样做。

    $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);
    

    【讨论】:

      【解决方案2】:

      我通过删除 $fillable 变量中的“图像”列解决了这个问题。在模型 Post.php 中

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

      【讨论】:

        【解决方案3】:

        .tmp 文件是您从本地计算机中选择的文件。因此,您需要为模型分配正确的路径以使用正确的 URL 存储它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-19
          • 1970-01-01
          • 2020-03-18
          • 2022-11-26
          • 2016-09-01
          • 1970-01-01
          • 2023-02-19
          • 1970-01-01
          相关资源
          最近更新 更多