@jerad
In Vue.js, you can check the extension of an uploaded file by using the FileReader
API along with the File
object. Here's an example of how you can achieve this:
1
|
<input type="file" @change="handleFileUpload"> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
methods: { handleFileUpload(event) { const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = () => { // Get the file extension const extension = file.name.split('.').pop(); // Now you can perform checks based on the file extension if (extension === 'jpg' || extension === 'jpeg') { // Perform some action } else if (extension === 'png') { // Perform some action } else { // File extension is not supported console.log('Unsupported file extension'); } }; reader.readAsDataURL(file); } } |
In this example, handleFileUpload
is triggered when a file is selected through the file input. The method gets the File
object from the event, and then creates a FileReader
object.
The FileReader.onloadend
event is fired when the file has been read successfully. Inside this event handler, you can extract the file extension by splitting the file name with periods and taking the last element. Then you can perform any actions or checks based on the file extension.
Note that in this example, the check is done for jpg
, jpeg
, and png
file extensions. You can modify it according to your requirements.