首页 > 解决方案 > foreach 语句导致多文件上传中未定义的变量 fileNameToStore

问题描述

我试图上传多个文件,所以我尝试稍微修改代码。但每次我添加 foreach($request->file('image') as $file)。我总是收到有关未定义变量的错误。我在下面附上了我的控制器代码,知道如何解决这个问题并进行多文件上传吗?

    if($request->hasFile('image'))
    {
        foreach($request->file('image') as $file)
        {
        $filenameWithExt =$request->file('image')->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extension = $request->file('image')->getClientOriginalExtension();
        $fileNameToStore = $filename. '_'.time().'.'.$extension;
        $path = $request->file('image')->storeAs('public/images', $fileNameToStore);
        }
    }
    $post = new Post;
    $post->image = $fileNameToStore;
    $post->save();
    return redirect('/dashboard')->with('success', 'Post Created!');

这是 create.blade.php

@extends('layouts.app')

@section('content')
    <h1>Upload Images</h1>
    {!! Form::open(['action' => 'PostsController@store', 'method'=> 'POST','enctype'=>'multipart/form-data'])!!}
    <div class="form-group">
        {{Form::file('image',['multiple'=>'true', 'files'=>'true'])}}
    </div>
    
   {{Form::submit('Submit',['class' => 'btn btn-success'])}}
   {!!Form::close()!!}

标签: phpsqllaravelvisual-studio-code

解决方案


如果我正确理解你。尝试添加fileNameToStore变量foreach

$errors = [];
$post = new Post;
if ($request->hasFile('cover_image')) {
    foreach ($request->file('cover_image') as $file) {
        $filenameWithExt =$request->file('image')->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extension = $request->file('image')->getClientOriginalExtension();
        $fileNameToStore = $filename. '_'.time().'.'.$extension;
        $path = $request->file('image')->move('public/images', $fileNameToStore);
        $post->cover_image = $fileNameToStore;
    }
    if (! fileNameToStore) {
        $errors[] = false;
    }
    if (count($errors) > 0) {
        return redirect('/dashboard')->with('error', 'Somthing went wrong!');
    }
}
$post->save()
return redirect('/dashboard')->with('success', 'Post Created!');

希望能帮到你。PS 替换imagecover_image.


推荐阅读