Laravel上传动态文件类型输入并存储到数据库

时间:2018-01-15 09:18:41

标签: laravel dynamic

这是我正在尝试使用的代码,我在我的数据库字段中得到'no-image.jpg',当我提交它时,我在表单中添加第二个动态行,我得到'未定义的偏移量: 1。除文件输入外,一切正常。

这是我的表单的一部分,它是动态的,我可以添加更多行:

    $input = $request->all();
    $pays = $request->input('pay');
    $paymentDates = $request->input('payDate');
    $account = $request->input('account');
    $attachment = $request->file('attachment_link');

    for($i=0; $i< count($input['pay']); $i++) {
        if ($request->hasFile($attachment[$i])) {
            $fileNameWithExt = $request->file($attachment[$i])->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extention = $request->file($attachment[$i])->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore = $filename . '_' . time() . '_' . $extention;
            // Upload Image
            $path = $request->file('attachment_link')->storeAs('public/content-images/products/', $fileNameToStore);
        } else {
            $fileNameToStore = 'no-image.jpg';
        }

        $payment = new Payment;
        $payment->file = $file;
        $prePayment = $pays[$i];
        $payment->payment = str_replace(',','',$prePayment);
        $payment->paymentDate = $paymentDates[$i];
        $payment->account = $account[$i];
        $payment->attachment_link = $fileNameToStore;
        $payment->save();
    }

这是我的控制者:

.subscribe(response => this.processList = response

1 个答案:

答案 0 :(得分:1)

试试这个 -

if (isset($attachment[$i])&&is_file($attachment[$i])) {
            $fileNameWithExt = $attachment[$i]->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extention = $attachment[$i]->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore = $filename . '_' . time() . '_' . $extention;
            // Upload Image
            $path = $attachment[$i]->storeAs('public/content-images/products/', $fileNameToStore);
        } else {
            $fileNameToStore = 'no-image.jpg';
        }