You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中上传两个文件字段并存储至同一张数据表

Laravel: Handle Multiple File Uploads (QR Image + Cloud QR Image)

Got it, let's get your two-file upload setup working smoothly in Laravel. We'll break this down into fixing the HTML form, refactoring the upload logic to avoid repetition, and saving both file paths to your database table.

Step 1: Update the HTML Form

First, your form is missing two critical pieces for file uploads: the enctype="multipart/form-data" attribute (required for sending files via form), and name attributes on your file inputs (Laravel uses these names to retrieve files from the request). Here's the corrected form:

<form action="{{ route('your.upload.route') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group">
        <label for="qrImage">QR Image</label>
        <input type="file" class="form-control-file" id="qrImage" name="qr_image">
    </div>
    <div class="form-group">
        <label for="cloudQrImage">Cloud QR Image</label>
        <input type="file" class="form-control-file" id="cloudQrImage" name="cloud_qr_image">
    </div>
    <button type="submit" class="btn btn-primary">Upload Images</button>
</form>

Step 2: Refactor Backend Upload Logic

Instead of writing duplicate code for each file, let's create a reusable helper function to handle the upload process. This keeps your code clean and easier to maintain.

Here's how your controller method should look:

use Illuminate\Http\Request;
use App\Models\QrCode; // Adjust this to match your model name

public function uploadImages(Request $request)
{
    // Optional but recommended: Validate file inputs
    $request->validate([
        'qr_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
        'cloud_qr_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);

    // Helper function to handle single file upload
    $processFileUpload = function ($fileInputName) use ($request) {
        if ($request->hasFile($fileInputName)) {
            $file = $request->file($fileInputName);
            $filenameWithExt = $file->getClientOriginalName();
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $file->getClientOriginalExtension();
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            
            // Store the file in storage/app/public/image
            $file->storeAs('public/image', $fileNameToStore);
            return $fileNameToStore;
        }
        // Return default file if no upload
        return 'nofile.jpg';
    };

    // Process both files using the helper
    $qrImagePath = $processFileUpload('qr_image');
    $cloudQrImagePath = $processFileUpload('cloud_qr_image');

    // Save both paths to your database table
    QrCode::create([
        'qr_image' => $qrImagePath,
        'cloud_qr_image' => $cloudQrImagePath,
        // Add any other fields from your table here
    ]);

    // Redirect back with success message
    return redirect()->back()->with('success', 'Images uploaded and saved successfully!');
}

Step 3: Prepare Your Database Table

Make sure your target table (e.g., qr_codes) has two string columns to store the file names:

  • qr_image (varchar, recommended length: 255)
  • cloud_qr_image (varchar, recommended length: 255)

Step 4: Update Your Eloquent Model

If you're using an Eloquent model, add the two fields to the $fillable array to allow mass assignment:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class QrCode extends Model
{
    protected $fillable = [
        'qr_image',
        'cloud_qr_image',
        // Include other fillable fields from your table
    ];
}

Quick Notes

  • Public Access: To make uploaded files accessible via the web, run php artisan storage:link to create a symbolic link from public/storage to storage/app/public.
  • Default File: Ensure nofile.jpg exists in storage/app/public/image, or adjust the default path to match your setup.
  • Validation: The rules enforce image-only uploads with a 2MB size limit—tweak these values to fit your requirements.

内容的提问来源于stack exchange,提问作者MJ DEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:08