【问题标题】:Laravel Upload Multiple Images Each With Different UserLaravel 上传多个图像,每个图像都有不同的用户
【发布时间】:2018-03-21 14:59:51
【问题描述】:

我正在尝试上传多张图片,每张图片都与不同的员工相关联。这是一个示例场景。我有 4 名员工。我想为 2 名员工添加不同的图像,而没有为休息 2 添加任何图像。这是现在发生的情况:

  1. 如果我不为任何一个添加图像,则所有 4 个都将获得默认图像(这是预期的)
  2. 如果我为 2 名员工添加不同的图片并留下另外 2 名员工,则所有 4 名员工都会获得最后上传的图片。
  3. 如果我为 1 名员工添加一张图片,而留下另外 3 张图片,则所有 4 张图片都会获得上传的图片。

对于第 2 和第 3 种情况,我希望为每个员工上传相关图像,如果未上传,则为默认图像。

这是表格:

@if ($employee->payment_option == 2)
   <div class="form-group{{ $errors->has('receipt') ? ' has-error' : '' }}">
   <input type="file" name="receipt[]" multiple>
       @if ($errors->has('receipt'))
           <span class="help-block">
               <strong>{{ $errors->first('receipt') }}</strong>
           </span>
       @endif
   </div>
@endif

这里是控制器存储方法

public function store(Request $request)
    {
        if ($request->hasFile('receipt')) {
            $files = $request->file('receipt');
            foreach ($files as $key => $file) {
                $extension = $file->getClientOriginalExtension();
                $fileNameWithExt = $file->getClientOriginalName();
                $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
                $fileName = $fileName.'_'.time().'.'.$extension;
                $folderpath  = 'public/images'.'/';
                $file->move($folderpath, $fileName);
            }
        }

        foreach ($request->employee_id as $key => $val) {
            $payrolls = new Payroll;
            $payrolls->employee_id = $val;
            if (!empty($request->receipt)) {
                $payrolls->receipt = $fileName;
            } else {
                $payrolls->receipt = 'noimage.jpg';
            }
            $payrolls->save();
        }
        return redirect('/');
    }

上传多个文件有几个问题,他们的解决方案很好。但是我需要上传与每个员工关联的每个文件。如果没有为员工上传文件,则应附上默认图片。

【问题讨论】:

  • 尝试使用uniqid()microtime() insted of time()
  • 谢谢。然而,这不是问题。这仅用于命名文件。与图片上传无关。

标签: php laravel laravel-5.6


【解决方案1】:
<input type="file" name="receipt[]" multiple>

我认为您对所有表单都使用相同的名称receipt...使用不同的名称,例如“receipt1,receipt2”...这样并相应地更改控制器。

【讨论】:

  • 我只想用一个表单上传所有。单独上传不是问题。
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 2017-06-25
  • 2020-12-27
  • 1970-01-01
  • 2021-08-01
相关资源
最近更新 更多