How to properly upload file from vue.js to laravel?

Member

by ryleigh , in category: PHP Frameworks , 4 months ago

How to properly upload file from vue.js to laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 4 months ago

@ryleigh 

To properly upload a file from Vue.js to Laravel, you can follow these steps:

  1. Create a file input field in your Vue.js component to allow users to select a file for upload:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <div>
    <input type="file" @change="onFileChange" />
  </div>
</template>

<script>
export default {
  methods: {
    onFileChange(event) {
      this.file = event.target.files[0];
    }
  }
}
</script>


  1. Send the file to Laravel using an HTTP request. You can use Axios, a popular HTTP client for Vue.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import axios from 'axios';

uploadFile() {
  const formData = new FormData();
  formData.append('file', this.file);

  axios.post('http://your-laravel-app-url/api/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
}


  1. Set up a route in your Laravel application to handle the file upload:
1
2
3
4
5
6
7
8
9
Route::post('/api/upload', function(Request $request) {
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        $fileName = $file->getClientOriginalName();
        $file->move(public_path('uploads'), $fileName);

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


Make sure to update the file upload route and file handling logic according to your application's requirements.


By following these steps, you should be able to properly upload a file from Vue.js to Laravel.