Display file name in Vue.js event.target.files

I am currently working on implementing an upload feature in my web application using vue 2. Here is a snippet of the code:

<label class="btn btn-xs btn-primary">
    <input type="file" name="attachment[]" @change="onFileChange" multiple/>
    Upload file
</label>

input[type="file"]  {
  display: none;
}


onFileChange() {
    this.reaction.attachment = event.target.files || event.dataTransfer.files;
}

Now, I want to display the file names that are included in the event.target.files object.

I have attempted the following:

<p v-for="file in reaction.attachment">
  {{ file.name }}
</p>

However, this does not seem to be working as expected. Looking into my Vue devtools, the attachment object appears like this:

attachment: FileList

Any ideas on how to make this work?

Thank you!

Answer №1

To retrieve the file name, use

document.getElementById("fileId").files[0].name
within the onFileChange function.

<label class="btn btn-xs btn-primary">
    <input type="file" name="attachment[]" id="fileId" @change="onFileChange" multiple/>
    Upload file
</label>
{{fileName}}

input[type="file"]  {
  height:0;
  weight:0;
  //OR
  display:none
}

When calling the function inside script, pass the event as a parameter.

onFileChange(event){
   var fileData =  event.target.files[0];
   this.fileName=fileData.name;
}

Answer №2

Feel free to explore the functional demonstration I've put together in the sandbox. You can test it with a single file or multiple files as well.

Answer №3

When choosing a single file, the following code can be used to display an input field and label with Bootstrap classes:

<input type="file" class="custom-file-input" id="idEditUploadVideo"
       v-on:change="videoChoosen">
<label class="custom-file-label" id="idFileName" for="idEditUploadVideo">
    [[videoFileName]]</label>

To show the selected file name in the label when a user selects a file, this JavaScript code can be implemented:

var vueVar = new Vue({
    el: '#idSomething',
    data: {
        videoFileName:''
    },
    methods: {
        videoChoosen(event){
            this.videoFileName = event.target.files[0].name;
        }
    },
    delimiters: ["[[", "]]"],
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this: array = [ { "name": "name", "value": "Olá" }, { "name": "age" ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Discover the best way to implement aliases for embedded base 64 images within HTML code

I am trying to incorporate Base64 embedded images into my HTML file, but the image sizes are over 200k, making the base64 data part very large. To address this issue, I would like to place these images in another tag, such as a script, and attach them at ...

Cart Quantity Can Only Be Updated Once Using Ajax

I am currently facing an issue with my page that allows users to increase and decrease the quantity of a product in their cart before proceeding to the checkout confirmation page. I am using Ajax for this functionality, where the backend manipulates the qu ...

Having trouble with Next.js getStaticProps? Getting a TypeError that says "Cannot read properties of undefined (reading 'map')"?

My latest project was built using create-next-app as a base. In the Blog.js page, I attempted to fetch data from https://jsonplaceholder.typicode.com/posts by utilizing the getStaticProps() function. I followed the instructions provided in this guide: htt ...

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

Ensuring phone number accuracy through a custom validator along with JavaScript validation

My phoneTextBox control has 4 TextBoxes: country code (1-3 digits), city code (1-7 digits), local number (1-7 digits) and an optional extra phone number (1-5 digits). The provided code is not functioning correctly. <script type="text/javascript& ...

Error occurs with iron-form when the submit button is within a div

I'm encountering an issue when trying to submit an iron-form. The error message I receive is: VM7938:3 Uncaught TypeError: Polymer.dom(...).localTarget.parentElement.submit is not a function This problem only occurs when the submit button is place ...

Tips for Isolating and Manipulating a Single Element in Array.map() with REACT.JS

Is there a way to change the style of a specific element in an array without affecting others when a button is clicked? I've been struggling with this because every time I try, it ends up changing all elements instead of just the one that was clicked. ...

Building with inline elements in Django

Within my Django 1.7 project, I am working with two closely connected models: Train and Passenger. The Passenger model has a ForeignKey linking it to the Train model. I am looking to create a view where users can add passengers and designate which train ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

How can I parse JSON in React using the Parse function?

I am currently working with three list components, and when I click on any item in the tree list, it displays the JSON data. However, I would prefer to view it in a parse format rather than JSON. I attempted to use let json = JSON.parse(this.props.node, n ...

Should React.cloneElement be used to pass new children or copy props.children?

I am having trouble understanding the third parameter "children" of React.cloneElement and how it relates to this.props.children. After reading a helpful guide on higher order components, I implemented the following code: render() { const elementsTre ...

Just initiate an API request when the data in the Vuex store is outdated or missing

Currently, I am utilizing Vuex for state management within my VueJS 2 application. Within the mounted property of a specific component, I trigger an action... mounted: function () { this.$store.dispatch({ type: 'LOAD_LOCATION', id: thi ...

Guide to retrieving the data type of a List Column using SharePoint's REST API

I am currently attempting to determine the type of columns in my SharePoint list so that I can accurately populate a form with the appropriate field types. During my research, I stumbled upon this informative article in the documentation which discusses ac ...

Combining Two External Components in VueJS: A Step-by-Step Guide

I am currently utilizing the Form Tags components from the bootstrap-vue framework. My goal is to integrate the vue-simple-suggest component (obtained via npm) with form tags in order to suggest words related to the user's query. Users should be able ...

Limiting the data obtained from the API to extract only the desired values

Using an API, I am retrieving customer information and displaying it in the console. The code snippet used for this operation is: if (this.readyState === 4) { console.log('Body:', this.responseText); } }; This returns a JSON object with v ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...