How to upload pdf file using laravel & vue.js?

by aniya.jaskolski , in category: PHP Frameworks , 6 months ago

How to upload pdf file using laravel & vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 6 months ago

@aniya.jaskolski 

To upload a PDF file using Laravel and Vue.js, you'll need to create a file upload form in your Vue.js component and then handle the file upload on the Laravel backend. Here's a step-by-step guide to help you accomplish this:

  1. Create a form in your Vue.js component that allows the user to select a PDF file and submit it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
  <div>
    <input type="file" @change="handleFileUpload">
    <button @click="uploadFile">Upload</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null
    };
  },
  methods: {
    handleFileUpload(e) {
      this.file = e.target.files[0];
    },
    uploadFile() {
      const formData = new FormData();
      formData.append('file', this.file);

      axios.post('/api/upload', formData)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
}
</script>


  1. Create a route in your Laravel routes file to handle the file upload:
1
Route::post('/api/upload', 'FileController@upload');


  1. Create a controller in Laravel to handle the file upload:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:pdf'
        ]);

        $file = $request->file('file');
        $fileName = $file->getClientOriginalName();
        $file->move(public_path('uploads'), $fileName);

        return response()->json(['message' => 'File uploaded successfully']);
    }
}


  1. Make sure you have Axios installed in your Vue.js project to handle HTTP requests. If you haven't already installed Axios, you can do so by running the following command:
1
npm install axios


  1. Run the Laravel backend and Vue.js frontend to test the file upload functionality. Select a PDF file in the form and click the "Upload" button. The file should be uploaded to the public/uploads directory in your Laravel project.


That's it! You've successfully uploaded a PDF file using Laravel and Vue.js.