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

如何在Quasar上传图片并通过Laravel保存至MySQL与服务器文件夹

Laravel + Quasar 图片上传与数据库存储方案

一、前端Quasar处理(文件提交)

你的q-file组件已绑定item.image,接下来需在提交表单时将文件包装成FormData发送给Laravel后端:

// 假设提交按钮绑定了submitForm方法
async submitForm() {
  const formData = new FormData();
  
  // 追加图片文件(name需和后端接收字段名一致,这里是poster_file)
  if (this.item.image) {
    formData.append('poster_file', this.item.image);
  }
  
  // 追加其他表单字段(如有,比如标题、描述)
  // formData.append('title', this.item.title);
  
  try {
    // 发送POST请求到Laravel API路由
    await this.$q.http.post('/api/items', formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 必须设置该请求头
      }
    });
    
    // 上传成功后的提示或表单重置
    this.$q.notify({ message: '图片上传并保存成功', color: 'positive' });
    this.item = {};
  } catch (error) {
    this.$q.notify({ message: '上传失败,请重试', color: 'negative' });
  }
}

二、后端Laravel处理

1. 配置文件存储软链接

Laravel默认将上传文件存在storage/app/public目录,该目录无法直接通过URL访问,需创建软链接到public/storage:

php artisan storage:link

2. 数据库迁移(添加图片字段)

确保模型对应的数据表有存储图片文件名的字段(比如image),迁移文件示例:

Schema::create('items', function (Blueprint $table) {
  $table->id();
  $table->string('image')->nullable(); // 存储图片文件名
  // 添加其他业务字段(如title、content等)
  $table->timestamps();
});

执行迁移:

php artisan migrate

3. 模型定义

在对应模型(比如Item.php)中设置可填充字段:

class Item extends Model
{
    use HasFactory;
    
    protected $fillable = ['image']; // 加入其他需要批量赋值的业务字段
}

4. 控制器处理上传与存储

在控制器(比如ItemController.php)的store方法中处理文件上传、存储和数据库写入:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Item;

public function store(Request $request)
{
    // 验证请求数据
    $validated = $request->validate([
        'poster_file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // 限制图片类型和大小(2MB)
        // 添加其他字段验证规则,如'title' => 'required|string'
    ]);

    $imageName = null;
    // 判断是否存在上传文件
    if ($request->hasFile('poster_file')) {
        // 生成唯一文件名(避免重复覆盖)
        $imageName = time() . '.' . $request->poster_file->extension();
        // 将文件存储到storage/app/public/images目录下
        $request->poster_file->storeAs('public/images', $imageName);
        // 如需获取访问URL,可使用:Storage::url("images/$imageName")
    }

    // 创建并保存模型实例
    $item = Item::create([
        'image' => $imageName,
        // 赋值其他业务字段,如'title' => $request->title
    ]);

    return response()->json([
        'message' => '数据保存成功',
        'item' => $item
    ], 201);
}

5. 定义API路由

在routes/api.php中添加POST路由:

use App\Http\Controllers\ItemController;

Route::post('/items', [ItemController::class, 'store']);

关键注意事项

  • 前端必须用FormData传递文件,且请求头设置为multipart/form-data
  • 后端验证规则可根据需求调整(比如图片大小、允许的格式)
  • 生成唯一文件名时,也可使用Str::random(20)替代time(),避免时间戳重复的极端情况
  • 展示图片时,可通过Storage::url("images/{$item->image}")获取完整访问URL

内容的提问来源于stack exchange,提问作者Sona Rijesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:56