Laravel 5.8 多张图片上传

Posted

技术标签:

【中文标题】Laravel 5.8 多张图片上传【英文标题】:Laravel 5.8 Multiple image upload 【发布时间】:2019-09-05 00:41:52 【问题描述】:

我是开发网站的新手,我真的很想学习!我无法弄清楚如何上传多张图片。我正在构建一个食谱应用程序,我目前在我的 RecipeController 中有一个工作文件上传,但是,我想调整它以便我可以上传多个。有人能指出我正确的方向吗?

配方控制器

public function store(Request $request)
            
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
            'ingredients' => 'required',
            'directions' => 'required',
            'recipeImage' => 'image|nullable|max:1999'
        ]);

        // Handle File Upload 
            if($request->hasfile('recipeImage'))
                // Get filename with extension
                $fileameWithExt = $request->file('recipeImage')->getClientOriginalName();
                // Get just filename
                $filename = pathinfo($fileameWithExt, PATHINFO_FILENAME);
                // Get just extension
                $extension = $request->file('recipeImage')->getClientOriginalExtension();
                // Filename to store
                $fileNameToStore = $filename . '_' . time() . '.' . $extension;
                // Upload Image
                $path = $request->file('recipeImage')->storeAs('public/recipe_images', $fileNameToStore);
             else 
                $fileNameToStore = 'noimage.jpg';
            

            $recipe = new Recipe;
            $recipe->author = auth()->user()->username;
            $recipe->title = $request->input('title');
            $recipe->description = $request->input('description');
            $recipe->ingredients = $request->input('ingredients');
            $recipe->directions = $request->input('directions');
            $recipe->recipeImage = $fileNameToStore;
            $recipe->prepTime = $request->input('prepTime');
            $recipe->cookTime = $request->input('cookTime');
            $recipe->servings = $request->input('servings');
            $recipe->calories = $request->input('calories');
            $recipe->user_id = auth()->user()->id;

            $recipe->save();

            $recipe->tags()->sync($request->tags, false);

            return redirect('/recipes')->with('success', 'Recipe Posted!');

如果用户选择上传,我正在尝试使我的数据库表“recipes”中的“recipeImage”列保存多个图像。我在网上找到了一些东西,但都涉及修改我的整个代码以使用 jQuery 插入数据库。有没有办法在我的控制器中做到这一点?还是我必须使用 jQuery 之类的东西才能使其工作?

谢谢!

【问题讨论】:

在您的代码中,您正在为单个图像上传而想要多个?? 是的!现在它只上传一张图片。我希望能够将多张图片上传到一个食谱。 你是处理多文件上传还是单文件上传 【参考方案1】:

最佳方法是为上传多张图片创建不同的recipe_images表,并在recipe_images表中将foreign key设为recipe_idRecipe有很多关系图片。

喜欢:

食谱表:

id | author | title | description | etc...

recipe_images 表:

id | recipe_id | image | timestamps

在您的配方模型中:

class Recipe extends Model

    public function images()
    
        return $this->hasMany('App\RecipeImages', 'recipe_id', 'id');
    

在您的 RecipeImages 模型中:

class RecipeImages extends Model

    public function recipe()
    
        return $this->belongsTo('App\Recipe');
    

然后在你的 blade 文件中:

<input type="file" name="recipeImage[]" multiple>

Controller在存储和数据库中存储多个图像:

public function store(Request $request)
        
    $this->validate($request, [
        'title' => 'required',
        'description' => 'required',
        'ingredients' => 'required',
        'directions' => 'required',
        'recipeImage' => 'image|nullable|max:1999'
    ]);

    $recipe = new Recipe;
    $recipe->author = auth()->user()->username;
    $recipe->title = $request->input('title');
    $recipe->description = $request->input('description');
    $recipe->ingredients = $request->input('ingredients');
    $recipe->directions = $request->input('directions');
    $recipe->prepTime = $request->input('prepTime');
    $recipe->cookTime = $request->input('cookTime');
    $recipe->servings = $request->input('servings');
    $recipe->calories = $request->input('calories');
    $recipe->user_id = auth()->user()->id;
    $recipe->save();

    // Handle multiple file upload
    $images = $request->file('recipeImage');
    foreach($images as $key => $image) 
        if ($request->hasFile('recipeImage')[$key] && $request->file('recipeImage')[$key]->isValid()) 
            // store image to directory.
            $path = $request->recipeImage[$key]->store('public/recipe_images/');
            $path = basename($path);

            // store image to database.
            $r_image = new RecipeImages();
            $r_image->recipe_id = $recipe->id;
            $r_image->image = $path;
            $r_image->save();
         else 
            return redirect()->back()->with('errors', 'Invalid Image file found!');
        
    

    $recipe->tags()->sync($request->tags, false);

    return redirect('/recipes')->with('success', 'Recipe Posted!');

create.blade.php 中的表单

<form method="POST" action=" action('RecipesController@store') " id="submitRecipeForm" enctype="multipart/form-data">
                @csrf

        <section class="createRecipe">

            <div class="createRecipeLeftBody">
                <div class="photoUploadInput">
                    <label for="imageUpload">
                        <input type="file" id="imageUpload" name="recipeImage[]" multiple>
                    </label>
                    <span>Add a photo of your recipe!</span>
                </div>


            <div class="container">
                <ul class="createRecipeInfo">
                    <div class="row">
                        <div class="col-lg-4">

                                <li>
                                    <label for="prep" class="prep">Prep Time</label>
                                    <input type="text" class="prep" id="prep" name="prepTime">
                                </li>

                                <li>
                                    <label for="cookTime">Cook Time</label>
                                    <input type="text" id="cookTime" name="cookTime">
                                </li>
                            </div><!-- col-lg-6 --> 

                            <div class="col-lg-4">
                                <li>
                                    <label for="servings">Serves: </label>
                                    <input type="text" id="servings" name="servings">
                                </li>

                                <li>
                                    <label for="calories">Calories/serving</label>
                                    <input type="text" id="calories" name="calories">
                                </li>
                            </div>

                    </div><!-- row -->
                    </ul>
                </div>
            </div><!-- container -->


            <div class="createRecipeBody"> 

                    <h2>Create Recipe <hr></h2>
                <fieldset>
                    <small class="errorMessage"> $errors->first('title') </small>
                    <label for="title">Give your creation a title</label>
                    <input type="text" name="title" id="title">
                </fieldset>

                <fieldset>
                        <small class="errorMessage"></small>
                        <label for="tags">Tags</label>
                        <select name="tags[]" id="tagsList" class="select2-multi" multiple="multiple">
                            @foreach($tags as $tag)
                                 <option value="$tag->id">$tag->name</option>
                            @endforeach
                        </select>
                </fieldset>

                <fieldset>
                    <small class="errorMessage"> $errors->first('description') </small>
                    <label for="description">Describe your creation</label>
                    <textarea name="description" id="description"></textarea>
                </fieldset>

                <fieldset>
                    <small class="errorMessage"> $errors->first('ingredients') </small>
                    <label for="ingredientList">List the ingredients</label>
                    <textarea name="ingredients" id="ingredientList" placeholder="Please list each ingredient on a seperate line"></textarea>
                </fieldset>

                <fieldset>
                        <small class="errorMessage"> $errors->first('directions') </small>
                        <label for="ingredientList">Directions</label>
                        <textarea name="directions" id="directions" placeholder="Please list each step on a seperate line"></textarea>
                </fieldset>


                <div class="terms">
                    <label class="authenticationCheck">
                        <input class="termsOfService" type="checkbox">
                        <span>
                            Public Recipe
                        </span>
                    </label>

                    <label class="authenticationCheck">
                        <input class="termsOfService" type="checkbox">
                        <span>Private Recipe</span>
                    </label>
                </div>
                <button class="submitRecipe" type="submit">Share your creation</button>
            </div>
        </section>
</form>

【讨论】:

我无法发布食谱。我点击提交,没有任何反应。由于顺序,它似乎无法处理控制器中的逻辑。我以前的代码有效,但使用新表和模型时,它不会上传。想法? 已添加到您的答案底部 dd($request-&gt;all());在 store 函数顶部检查所有请求是否来自表单?

以上是关于Laravel 5.8 多张图片上传的主要内容,如果未能解决你的问题,请参考以下文章

在Laravel 5.8中无法上传图片?

laravel 8中多张图片上传的问题

Laravel Vue 多张图片上传失败,每个图片都有一个 NULL 值

Laravel 5.2 中的多张图片上传

Laravel 4 上传 1 张图片并保存为多张 (3)

带删除和预览的多张图片上传 Laravel