View a photo in advance of its upload using VUEjs

Although this question has been raised before, I am struggling with implementing the code in vuejs. Despite my efforts, I have not been able to achieve any results yet. I have included my code below. Could someone please assist me? Here is my code. Thanks

html

<template>
<div class="fileUpload">
    <b-container fluid>

        <h4>Image Overview</h4>
        <b-button @click="$refs.fileInput.click()" class="btn-right">Select an image</b-button>

        <b-table @row-clicked="viewImage" striped hover :items="images" :fields="image_fields"></b-table>

        <input style="display: none" ref="fileInput" type="file" @change="fileSelected" enctype="multipart/form-data">
        <b-button variant="success" class="btn-right" @click="uploadImage" method="post">Upload image</b-button>


    </b-container>
</div>

js

<script>
export default {
    name: 'listImage',
    data() {
        return {
            selectedFile: null,
            images: [],
            image_fields: ['id', 'name'],
            total_images: 1               
        }
    },
    methods: {
        fileSelected(evt) {
            evt.preventDefault()
            console.log(evt);
            this.selectedFile = evt.target.files[0]
        },
        uploadImage() {
            var data = new FormData();
            data.append('image', this.selectedFile, this.selectedFile.data)
            var token = sessionStorage.getItem('token')
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            window.API.post('https://110.10.56.10:8000/images/?token=' + token, data, config)
                .then(response => this.$router.push('/listImage'))
                .catch((error) => {
                    console.log(JSON.stringify(error))
                })
        }
    }
}

Answer №1

Be aware that not all image types can be displayed by browsers, such as tiff files which may not work with this method.

Here are the steps you need to follow:

  • Add a file input with a @change listener
  • In the onChange event, create an object URL
  • Use this URL to display the image

const vm = new Vue({
  el: '#app',
  data() {
    return {
      url: null,
    }
  },
  methods: {
    onFileChange(e) {
      const file = e.target.files[0];
      this.url = URL.createObjectURL(file);
    }
  }
})
body {
  background-color: #e2e2e2;
}

#app {
  padding: 20px;
}

#preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

#preview img {
  max-width: 100%;
  max-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <input type="file" @change="onFileChange" />

  <div id="preview">
    <img v-if="url" :src="url" />
  </div>
</div>

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

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Error in Angular Due to Circular Reference in JSON

I'm currently working on integrating a tree structure in AngularJS. The goal is to construct the tree by dynamically adding nodes based on user input from an Angular Select element. Here is the specific operation I'm trying to accomplish: var a ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

Error with Cross-Origin Resource Sharing (CORS) upon inserting a parameter within an Express application

I'm completely stumped as to why this isn't functioning properly. My express app is deployed on Heroku and here's the code: var urlMetadata = require('url-metadata') var express = require('express') var cors = require( ...

Implement Vue JS to set default value(s) in an array

While browsing through Stack Overflow, I've noticed many questions related to Vue JS and selecting a default single value from an Array. My situation is a bit different - I need to compare each item's array groups with an array containing ALL THE ...

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

What is the best way to implement an undo-list using arrays?

My current project involves creating a paint program in JavaScript, and I am aiming to implement an undo function rather than just an eraser. How can I store events in an array and then enable the deletion of each event individually? I have a dropdown men ...

I'm having trouble with the routing of a Node.js REST API built with Express and Mongoose

I am currently in the process of constructing a RESTful webservice by following a tutorial that can be found at: However, I have encountered an issue where it is returning a CANNOT GET/ reports error. Despite my efforts to troubleshoot and rectify the pro ...

It appears that the jQuery $.get and $.post methods are not functioning as expected

Hey everyone, I'm facing an issue with two PHP session variables that I need to clear on click. I've attempted using both $.get and $.post AJAX methods to trigger an external PHP script that should reset the values of these session variables. How ...

Is there a way to integrate jQuery and Javascript into a Firefox add-on?

Having trouble creating a new element on the page? After checking both the page and domain during onload, it seems that everything is in order. But how can you successfully create a new element in the correct window page? window.addEventListener("load", f ...

having difficulty obtaining the keyCode/key event while input event is triggered

Recently, I encountered a challenge where I attempted to log the event key during an input bound event on the input. Below is the code snippet of what I tried: <div id="app"> <input @input="onInput" @keyup="onKeyUp" type="text"> </div&g ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

Developing a React Native app using Expo and Firebase? Learn how to prevent Firebase details from

I have encountered a problem with my code while working on the user edit profile page in my react native app. The issue I am facing is related to displaying the previously inputted firebase details from the collection in the text input fields when the user ...

Gathering information in a non-blocking manner with $.ajax() in rails version 3.2.2

Currently, I am delving into the realm of asynchronous data retrieval in my Rails 3.2.2 project. As a newcomer to both JavaScript and jQuery, I've stumbled upon an issue where JavaScript is unable to fetch data from a different domain server. To overc ...

The useNavigate() function seems to be failing to redirect to the '/protected' route

The issue lies in the redirection process after receiving the token from the API. Although the token is successfully saved in local memory, the redirect to the intended page does not occur as expected. Instead, a manual window refresh is required to naviga ...

Passing a variable to a component attribute in Vue.js

Is there a way to pass variables to a component in Vue.js without using props? Is this even possible? Take a look at app.js below: import PlayingField from '../app/components/PlayingField' import GameConfig from '../../gameConfig' ne ...

Using the Unsigned Right Shift Operator in PHP (Similar to Java/JavaScript's >>> Operator)

Before marking this as a duplicate, please take a moment to read the information below and review my code * my updated code! The issue I am facing is that I need to implement Java/JavaScript '>>>' (Unsigned Right Shift / Zero-fill Rig ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...