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

Laravel9+Inertia+Vue3课程视频上传失败问题求助

视频上传失败且无法存入数据库的排查与修复方案

1. 验证CourseVideo模型配置

  • 确保模型与Course的关联关系正确定义:
// app/Models/CourseVideo.php
public function course()
{
    return $this->belongsTo(Course::class);
}
  • 检查$fillable属性是否包含所有需要存入的字段,避免批量赋值被拦截:
protected $fillable = ['course_id', 'video_path', 'title', 'duration'];

2. 检查控制器存储逻辑

  • 确认控制器正确处理文件上传与数据入库,包含验证、文件存储、模型创建完整流程:
// app/Http/Controllers/CourseVideoController.php
public function store(Request $request)
{
    // 验证请求合法性
    $validated = $request->validate([
        'course_id' => 'required|exists:courses,id',
        'video' => 'required|file|mimes:mp4,avi,mov|max:10240', // 根据需求调整格式和大小限制
        'title' => 'nullable|string|max:255',
    ]);

    // 处理文件上传
    if ($request->hasFile('video') && $request->file('video')->isValid()) {
        $storagePath = $request->file('video')->store('course_videos', 'public');
        
        // 写入数据库
        CourseVideo::create([
            'course_id' => $validated['course_id'],
            'video_path' => $storagePath,
            'title' => $validated['title'] ?? null,
        ]);

        return response()->json(['message' => '视频上传成功'], 201);
    }

    return response()->json(['error' => '视频文件无效'], 400);
}
  • 可在控制器开头添加dd($request->all()),确认前端传递的数据是否完整包含视频文件与course_id。

3. 确认迁移文件正确性

  • 检查CourseVideo表的迁移是否包含必要字段与正确的外键关联:
// database/migrations/xxxx_xx_xx_xxxxxx_create_course_videos_table.php
public function up()
{
    Schema::create('course_videos', function (Blueprint $table) {
        $table->id();
        $table->foreignId('course_id')->constrained('courses')->onDelete('cascade');
        $table->string('video_path');
        $table->string('title')->nullable();
        $table->integer('duration')->nullable();
        $table->timestamps();
    });
}
  • 执行php artisan migrate:status确认迁移已成功执行,若未执行则运行php artisan migrate。

4. 排查前端组件请求逻辑

  • 确保表单使用multipart/form-data编码,这是文件上传的必要条件:
<!-- Create.vue -->
<form @submit.prevent="uploadVideo" enctype="multipart/form-data">
    <input type="hidden" v-model="courseId" name="course_id">
    <input type="file" name="video" @change="handleVideoSelect">
    <input type="text" v-model="videoTitle" name="title">
    <button type="submit">上传视频</button>
</form>
  • 确认axios请求正确传递FormData对象,且设置了正确的请求头:
// Create.vue 脚本部分
data() {
    return {
        courseId: 1, // 替换为实际课程ID
        videoFile: null,
        videoTitle: ''
    }
},
methods: {
    handleVideoSelect(e) {
        this.videoFile = e.target.files[0];
    },
    async uploadVideo() {
        const formData = new FormData();
        formData.append('course_id', this.courseId);
        formData.append('video', this.videoFile);
        formData.append('title', this.videoTitle);

        try {
            await axios.post('/api/course-videos', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            alert('上传成功');
        } catch (err) {
            console.error('上传失败:', err.response?.data || err.message);
        }
    }
}

5. 验证路由配置

  • 确认路由指向正确的控制器方法,若为API路由需放在routes/api.php中:
// routes/api.php
Route::post('/course-videos', [CourseVideoController::class, 'store']);
// 若为课程关联路由,可定义为:
Route::post('/courses/{course}/videos', [CourseVideoController::class, 'store']);
  • 检查是否有中间件限制(如auth:sanctum),若前端未携带认证令牌会导致请求被拦截。

6. 调试与日志检查

  • 查看Laravel日志文件(storage/logs/laravel.log),排查是否有SQL错误、文件权限问题或验证失败信息。
  • 使用浏览器开发者工具的Network面板,检查请求的状态码、请求参数及响应内容,确认请求是否正常发送到后端。

内容的提问来源于stack exchange,提问作者salaheddine el jettioui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:35:23