如何使用 laravel vue api 上传文件?

How to upload file using laravel vue api?

我正在尝试制作一个能够使用表单上传文件的表单

我能够存储字符串、整数数据,但我有点迷失了我需要为控制器和视图提供的方式

这是添加模板:

<template>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4>Add Category</h4>
            </div>
            <div class="card-body">
                <form
                    @submit.prevent="create"
                    enctype="multipart/form-data"
                >
                    <div class="row">
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>Title</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.title"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>Description</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.description"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>name</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.name"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>path</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.path"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>File</label>
                                <input
                                    type="file"
                                    class="form-control"
                                    v-on:change="onChange"
                                />
                            </div>
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                Save
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
name: "add-category",
data() {
    return {
        category: {
            title: "",
            description: "",
            name: "",
            file: "",
        }
    };
},
methods: {
    async create() {
        await this.axios
            .post("/api/category", this.category)
            .then(response => {
                this.$router.push({ name: "categoryList" });
            })
            .catch(error => {
                console.log(error);
            });
    }
}
};
</script>

这是数据库 table:

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('description');
        $table->string('name')->nullable();
        $table->string('path')->nullable();  
        $table->timestamps();
    });
}

控制器:

public function store(Request $request)
{
    $category = Category::create($request->post());
    return response()->json([
        'message'=>'Category Created Successfully!!',
        'category'=>$category
    ]);
}

型号:

class Category extends Model
{
use HasFactory;

protected $fillable = ['title','description','name','path'];
}

应用程序:

require('./bootstrap');
import vue from 'vue'
window.Vue = vue;

import App from './components/App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './routes';

Vue.use(VueRouter);
Vue.use(VueAxios, axios);

const router = new VueRouter({
mode: 'history',
routes: routes
});

const app = new Vue({
el: '#app',
router: router,
render: h => h(App),
});

如有必要,我可以提供更多代码

当前代码正在运行并存储在数据库中,但唯一的问题是上传文件

您只需要使用 FomrData。 像这样

const formData = new FormData;
formData.append('file_index', this.uploadedFileIndex);
formData.append('file', file);
formData.append('user_tz', Intl.DateTimeFormat().resolvedOptions().timeZone);
formData.append('file_tags', JSON.stringify(fileTagIds));
formData.append('in_folder', this.inFolder);
formData.append('favorites', this.favorites);

将您所有的表单数据附加到 fromData 中,然后发送您的 fromData

首先你需要像@change="onChange($event)一样调用onchnage函数。 其次,您需要将代码放入 onchange 函数中,如下所示。 onChange(event) {this.category.file = event.target.file;} 最后,您需要使用 FormData 并在 create 函数中的 api 中传递 Header,如下所示。

编辑

methods: {
    async create() {
        var form = new FormData();
        form.append("title", this.category.title);
        form.append("description", this.category.description);
        form.append("name", this.category.name);
        form.append("file", this.category.file);
        var config = {
            header: { "Contect-type": "multipart/form-data" },
        };
        await this.axios.post("/api/category", form, config).then(response => {
            this.$router.push({ name: "categoryList" });
        }).catch(error => {
            console.log(error);
        });
    },
    onChange(event) {
       this.category.file = event.target.file;
    }
}