Submitting Files to the API using Vue.js

I have the following code in Vue.js and I am trying to upload a file, but my issue is that I want to save the filename of the uploaded file to the JSON API using a POST method. Is there a way to achieve this? Thank you in advance.

<div class="input-file">
    <input class="input-file__input" ref="file" type="file">
    <div class="input-file__button" @click="selectFile()"></div>
  </div>

  <script>
  selectFile(){
      let fileInputElement = this.$refs.file;
      fileInputElement.click(); // I want to send this filename to the API POST method
      // ...
    },
    </script>

Answer №1

Imagine you are working with an input element that has the id 'upload', here is what you can do:

log_file_name() {
  const path = document.getElementById('upload').value;
  if (path) {
    let startIndex = (path.indexOf('\\') >= 0 ? path.lastIndexOf('\\') : path.lastIndexOf('/'));
    let filename = path.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
      filename = filename.substring(1);
    }
    console.log(filename);
  }
}
<input class="input-file__input" id="upload" @change="log_file_name()" ref="file" type="file">

Answer №2

To retrieve the selected file, one option is to listen for the change event:

<input class="input-file__input" ref="file" type="file" @change="changeFile">
changeFile(event) {
  const selectedFile = event.target.files[0];
}

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

Output the word 'Days', 'Months', or 'Years' depending on the value of N, which represents the number of days

I am currently utilizing moment.js in conjunction with vue 3. I've implemented a function that calculates the disparity between two dates. The functionality works as expected, but here's where my query comes in. The function is structured like so ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

Exploring the World of GiantBomb APIs

I have successfully created an account and obtained my API key. I am looking to implement a basic search functionality on my webpage, where users can enter a search query and click a button to display the game title and image. You can find more informatio ...

Seeking a method to display a tooltip exclusively when the element is cut off

Can someone assist me with finding a solution to display the tooltip element only when the span element is truncated? <q-td v-for="(col,index) in props.cols" :key="col.name" :props="props"> <span class="t ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

Passing props from a Higher Order Component (HOC) to child components in next.js using get

I am looking to implement an HOC (Higher Order Component) for pages within my application that can provide some information stored in local storage, especially when the pages are not being server-side rendered. The challenge I'm encountering is that ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Does the layout.tsx file in Next JS only affect the home page, or does it impact all other pages as well?

UPDATE After some troubleshooting, I've come to realize that the issue with my solution in Next JS 13 lies in the structure of the app. Instead of using _app.tsx or _document.tsx, the recommended approach is to utilize the default layout.tsx. Althou ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Identify input elements that specifically contain an onclick event

Several of the input elements on my page have a function called setSomeFunction() that either shows or hides certain divs when clicked. I know I can locate all the input elements using document.getElementsByTagName("input") and store them in an array. How ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Is being unfazed by work a common occurrence?

After completing a complex cycle that processes data from the database and writes it to an array, I encounter a situation where the array processing function is triggered before the array is fully populated. This forces me to use setTimeout() for proper ti ...

I encountered an error stating that ".then" is not defined during my attempt to save

Just starting out with node.js and I encountered an issue: TypeError: Cannot read property 'then' of undefined This is the code snippet causing the problem: router.post("/signup", (req, res) => { const userRegister = new UserRegister({ ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

Adding a total row to a Vuetify datatable

Struggling to incorporate a totals row using this framework, but it doesn't seem to be supported out of the box. The workaround I've come up with doesn't quite hit the mark... <v-data-table :headers="headers" :items="desserts" ...

Vue component failing to display data passed as props

As a Vue beginner, I ventured into creating a custom component and attempted to bind everything just like in the basic Vue CLI template. Here is my code snippet. Circle.vue <template> <div :style="custom"> </div> </template&g ...

How can you use jQuery.ajax to solely fetch the status code without downloading the entire document?

My application relies on the use of jQuery.ajax to check if a particular resource exists by constantly polling it. Once the resource is no longer returning a 404 status code, the app redirects to view that resource. However, I am concerned about downloadin ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: The challenge now is figuring out what exactly to search for i ...