Laravel 및 Vue.js를 사용하여 파일을 업로드하는 방법

Laravel 및 Vue.js를 사용하여 파일을 업로드하는 방법을 알아보세요. 이 단계별 가이드에서는 널리 사용되는 두 가지 프레임워크를 사용하여 강력한 파일 업로드 애플리케이션을 만드는 방법을 보여줍니다.

laravel과 vue js를 이용한 파일업로드에 대해 배워보겠습니다. laravel vue axios 파일 업로드 예시를 만들어 보겠습니다. axios를 사용하여 게시 요청을 쉽게 실행하고 파일 객체를 매개변수로 전달할 수 있으므로 laravel 5, laravel 6, laravel 7, laravel 8, laravel 9 및 laravel 10을 사용하여 서버에 파일을 저장할 수 있습니다.

1단계: 라라벨 프로젝트 설치

먼저 다음 명령을 사용하여 Laravel 애플리케이션을 설치합니다. 터미널 또는 명령 프롬프트를 열고 다음 명령을 실행합니다.

composer create-project --prefer-dist laravel/laravel blog

2단계: 경로 생성

두 번째 단계에서는 하나의 게시 경로를 만들고 파일 업로드 코드를 작성합니다. 그러면 해당 파일에 새로운 경로를 추가해 보겠습니다.

경로/web.php

Route::post('formSubmit','FileController@formSubmit');

3단계: FileController 생성

이 단계에서는 이제 formSubmit 메소드를 사용하여 FileController를 생성했습니다. 이 메소드에서는 서버에 저장 파일의 코드를 작성합니다. 이제 컨트롤러를 만들어 보겠습니다.

앱/Http/Controller/FileController.php

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
   
class FileController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function formSubmit(Request $request)
    {
        $fileName = time().'.'.$request->file->getClientOriginalExtension();
        $request->file->move(public_path('upload'), $fileName);
              
        return response()->json(['success'=>'You have successfully upload file.']);
    }
}

4단계: NPM 구성

여기에서는 먼저 vue js 설정을 추가한 다음 npm을 설치해야 하므로 프로젝트에서 다음 명령을 실행해 보겠습니다.

설치 보기:

php artisan preset vue

npm을 설치합니다:

npm install

5단계: app.js 및 구성 요소에 쓰기

이 단계에서는 app.js에 코드를 작성한 다음 vue js 구성 요소를 생성합니다. 따라서 두 파일을 모두 생성하고 다음 코드를 입력해 보겠습니다.

리소스/자산/js/app.js

 
require('./bootstrap');
 
window.Vue = require('vue');
 
Vue.component('example-component', require('./components/ExampleComponent.vue'));
 
const app = new Vue({
    el: '#app'
});

자원/자산/js/구성 요소/ExampleComponent.vue

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Laravel Vue JS File Upload Example - codequs.com</div>
    
                    <div class="card-body">
                        <div v-if="success != ''" class="alert alert-success" role="alert">
                          {{success}}
                        </div>
                        <form @submit="formSubmit" enctype="multipart/form-data">
                        <strong>Name:</strong>
                        <input type="text" class="form-control" v-model="name">
                        <strong>File:</strong>
                        <input type="file" class="form-control" v-on:change="onFileChange">
    
                        <button class="btn btn-success">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
   
<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        },
        data() {
            return {
              name: '',
              file: '',
              success: ''
            };
        },
        methods: {
            onFileChange(e){
                console.log(e.target.files[0]);
                this.file = e.target.files[0];
            },
            formSubmit(e) {
                e.preventDefault();
                let currentObj = this;
   
                const config = {
                    headers: { 'content-type': 'multipart/form-data' }
                }
    
                let formData = new FormData();
                formData.append('file', this.file);
   
                axios.post('/formSubmit', formData, config)
                .then(function (response) {
                    currentObj.success = response.data.success;
                })
                .catch(function (error) {
                    currentObj.output = error;
                });
            }
        }
    }
</script>

6단계: Welcome.blade.php 업데이트

마지막 단계에서는 Welcome.blade.php 파일을 업데이트하겠습니다. 이 파일에서는 app.js 파일을 이용해서 사용할 것이므로 업데이트해보겠습니다.

리소스/뷰/welcome.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel Vue JS File Upload Example - codequs.com</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="app">
            <example-component></example-component>
        </div>
        <script src="{{asset('js/app.js')}}" ></script>
    </body>
</html>

이제 app.js 파일을 업데이트하려면 아래 명령을 실행해야 합니다.

npm run dev

공용 디렉토리에 "업로드" 폴더를 생성했는지 확인하세요.

이제 예제를 확인하고 데모를 확인하고 여기에서 무료 코드를 다운로드할 수 있습니다: GitHub 코드

#laravel #vue #vuejs 

1.05 GEEK