Laravel Vue Display Image from Storage
In Laravel, it is common to store images and other files in the storage directory. To display an image stored in the storage directory using Vue, you will need to follow these steps:
1. Save the Image to the Storage Directory
Before displaying the image, make sure it is saved in the correct directory in storage. You can save the image using Laravel’s file storage helpers or using any file handling library of your choice.
2. Create a Route in Laravel
Create a route in your Laravel application that will return the image from the storage directory. This can be done in your web.php or api.php routes file.
Route::get('/storage/{filename}', function($filename) {
$path = storage_path('app/public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
In this example, we define a route that takes a {filename} parameter. It first checks if the file exists in the storage directory, and if not, it returns a 404 response. If the file exists, it reads the file and sets the appropriate Content-Type header before returning the file as a response.
3. Use the Image in Vue Component
In your Vue component, you can now use the image by making an HTTP request to the Laravel route using the image’s filename.
import axios from 'axios';
export default {
data() {
return {
imageUrl: ''
};
},
mounted() {
this.fetchImage();
},
methods: {
fetchImage() {
const filename = 'your-image-filename.jpg';
axios.get(`/storage/${filename}`, { responseType: 'blob' })
.then(response => {
const blobUrl = URL.createObjectURL(response.data);
this.imageUrl = blobUrl;
})
.catch(error => {
console.error(error);
});
}
}
}
In this example, we use the axios library to make a GET request to the Laravel route that we created earlier. The responseType is set to ‘blob’, which means that the response data will be treated as a Blob object in JavaScript. We then create a blob URL from the response data and set it as the value of the imageUrl property.
4. Display the Image in the Vue Component
Finally, you can display the image in your Vue component using the imageUrl property.
<template>
<div>
<img :src="imageUrl" alt="Image" />
</div>
</template>
In this example, we use the <img>
HTML tag and bind the src attribute to the imageUrl property. This will display the image in the Vue component.
That’s it! Now you should be able to display an image from the storage directory in Laravel using Vue.