Home > Enterprise >  How to upload file using laravel vue api?
How to upload file using laravel vue api?

Time:04-27

i'm trying to make a form with the ability to upload files using form

i'm able to store string, int data but i'm a bit lost with the way that i need to provide for the controller and the view

this is the add template:

<template>
<div >
    <div >
        <div >
            <div >
                <h4>Add Category</h4>
            </div>
            <div >
                <form
                    @submit.prevent="create"
                    enctype="multipart/form-data"
                >
                    <div >
                        <div >
                            <div >
                                <label>Title</label>
                                <input
                                    type="text"
                                    
                                    v-model="category.title"
                                />
                            </div>
                        </div>
                        <div >
                            <div >
                                <label>Description</label>
                                <input
                                    type="text"
                                    
                                    v-model="category.description"
                                />
                            </div>
                        </div>
                        <div >
                            <div >
                                <label>name</label>
                                <input
                                    type="text"
                                    
                                    v-model="category.name"
                                />
                            </div>
                        </div>
                        <div >
                            <div >
                                <label>path</label>
                                <input
                                    type="text"
                                    
                                    v-model="category.path"
                                />
                            </div>
                        </div>
                        <div >
                            <div >
                                <label>File</label>
                                <input
                                    type="file"
                                    
                                    v-on:change="onChange"
                                />
                            </div>
                        </div>
                        <div >
                            <button type="submit" >
                                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>

this is the database 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();
    });
}

controller:

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

model:

class Category extends Model
{
use HasFactory;

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

app:

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),
});

i can provide more code if necessary

the current code is working and storing in database but the only problem is uploading a file

CodePudding user response:

You just need to use FomrData. Something like this

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);

Append all your form data in fromData,and then send your fromData

CodePudding user response:

Firstly you need to call onchnage function like @change="onChange($event). Secondly you need to put code in onchange function like below. onChange(event) {this.category.file = event.target.file;} And last you need to use FormData and pass Header in api in create function like below.

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);
    });
}
  • Related