【问题标题】:Laravel storing tmp filename in databaseLaravel 在数据库中存储 tmp 文件名
【发布时间】:2017-10-05 07:45:26
【问题描述】:

上传脚本正在运行,文件也以正确/所需的名称保存。但是,在将数据存储在数据库中时,它会存储 .tmp 文件名

控制器代码:

public function store(Request $request)
{
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required',
        'featured_image' =>'image|max:1999'
    ]);

    $post = new Post;

    if ($request->hasFile('featured_image')) {
        $image = $request->file('featured_image');
        // dd($image);

        $filename = time(). '.' .$image->getClientOriginalExtension();
        // dd($filename);
        $location = public_path('images/' . $filename);
        // dd($location);
        Image::make($image)->resize(800, 400)->save($location);
        // dd($image);

        $post->image = $filename;

        // dd($post);
    }

    auth()->user()->publish(
        new Post(request(['title', 'body', 'featured_image']))
    );

    session()->flash('message', 'your post has now been published');
    return redirect('/');
}

它将文件名存储为C:\xampp\tmp\phpD837.tmp。怎么了?

【问题讨论】:

  • 您确定它存储/更新实际的.tmp 文件名吗?因为我在这里看到的是:你不保存$post->save()
  • 不要偷懒复制代码而不是添加图片!

标签: php laravel


【解决方案1】:

您使用正确的图像文件名创建一个新的Post

$post = new Post;
....
$post->image = $filename;

但是当你保存到数据库时,你根本不使用 $post 数据:

auth()->user()->publish(
    new Post(request(['title', 'body', 'featured_image']))
);

所以基本上你使用 POST 数据创建另一个新的 Post,其中包括临时 PHP 文件名,忽略第一个 Post,它具有你想要的文件名。

尝试类似:

$post = new Post;
....
$post->image = $filename;
$post->title = $request->title;
$post->body  = $request->body;

auth()->user()->publish($post);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2021-08-24
      • 2022-11-25
      相关资源
      最近更新 更多