首页 > 解决方案 > 使用laravel php循环将变量添加到数据库

问题描述

出于某种原因,我的脚本返回 noimage.jpg 并且没有存储图像。不太清楚为什么?它构造了正确的文件名,但由于某种原因似乎与这两个术语不匹配?例如,它构造了“image1”,但是当“image1”字段被填写时,看不到它们匹配吗?

用户上传照片:

   <div class="section4 ">
        <div class="row">
            <div class="col-lg-3">
                <div class="form-group">
                    {{Form::file('image1.jpg')}}
                </div>
                <div class="form-group">
                    {{Form::file('image2')}}
                </div>
                <div class="form-group">
                    {{Form::file('image3')}}
                </div>
                <div class="form-group">
                    {{Form::file('image4')}}
                </div>
            </div>

        </div>
        </div>

控制器:

for($i=1; $i<=16; $i++){
        $filenamestr = (string)('image'.$i);
        if($request->hasFile($filenamestr)){
            // Get filename with the extension
            $filenameWithExt = $request->file('image'.$i)->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('image'.$i)->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $filename.'_'.time().'.'.$extension;
            // Upload Image
            $path = $request->file('image'.$i)->storeAs('public/cover_images', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }
    }

标签: phphtmlmysqllaravel

解决方案


的最终值$fileNameToStore被设置为循环的第 16 次迭代,即noimage.jpg. 但是,如果您的图像存在,它看起来仍然应该被存储。

您可以通过创建要存储的文件名数组来解决第一个问题:

for($i=1; $i<=16; $i++){
    $filenamestr = (string)('image'.$i);
    if($request->hasFile($filenamestr)){
        // Get filename with the extension
        $filenameWithExt = $request->file('image'.$i)->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        // Get just ext
        $extension = $request->file('image'.$i)->getClientOriginalExtension();
        // Filename to store
        $fileNameToStore[$i]= $filename.'_'.time().'.'.$extension;
        // Upload Image
        $path = $request->file('image'.$i)->storeAs('public/cover_images', $fileNameToStore[$i]);
    } else {
        $fileNameToStore[$i] = 'noimage.jpg';
    }
}

dd($fileNameToStore);

对于第二个问题,请记住检查您的表单是否已<form enctype="multipart/form-data"...设置。cover_images还要检查服务器对您的文件夹有写访问权。

还要检查您的第一个输入的名称,因为它最后不应该有.jpg

最后,考虑使用$request->file('image'.$i)->isValid()before storage 来检查文件是否有效。

最后

考虑使用数组输入而不是编号字段。即调用每个字段{{Form::file('image[]')}}并使用 Laravel 对dot符号的支持或foreach($request)->file()


推荐阅读