Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the uploaded image is not displayed immediately as expected. You can see a demo of the desired functionality here: https://codepen.io/Atinux/pen/qOvawK/

Unfortunately, instead of the image being displayed, I encounter the following error:

http://localhost:8080/image Failed to load resource: the server responded with a status of 404 (Not Found)

If it is attempting to retrieve the image from the root directory, could the problem be that I am not saving it there? How can I go about resolving this issue?

Here's a snippet from my 'page_image.ts' file:

require("./page_image.scss");
import Vue = require("vue");
import {Injections} from "../../init";

export const PageImage = {
template: require("./page_image.haml"),
data: function () {
    return {
        image: ''
    }
},

created() {
    Injections.HeaderTextManager.setHeader("Videos");
    Injections.HeaderTextManager.clearDescription();
},

methods: {
    onFileChange(e:any) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
            return;
        this.createImage(files[0]);
    },
    createImage(file:any) {
        var image = new Image();
        var reader = new FileReader();
        var vm = this;

        reader.onload = (e:any) => {
            vm.image = e.target.result;
        };
        reader.readAsDataURL(file);
    },
    removeImage: function (e:any) {
        this.image = '';
    }
}
};

And here's what I have in my 'page_image.haml' file:

.page-image
  .row
  .col-xs-12
    .box
      .box-header
        %div(v-if="!image")
          %h3.box-title Upload an image
          %input(type="file" v-on:change="onFileChange")
        %div(v-else)
          %img(src="image" name="image")
          %img {{image}}
          %button(v-on:click="removeImage") Remove image

Answer №1

I am not familiar with haml, and I don't typically use typescript in conjunction with vue.js. Therefore, I'm unable to provide a straightforward solution.

However, I have included a functional jsFiddle demonstration that employs FileReader with vue.js to enable an instant preview: https://jsfiddle.net/mani04/5zyozvx8/

You can utilize the above example for troubleshooting purposes.

This is how it operates: In order for FileReader to function correctly, we need to access the DOM element for input. This objective can be achieved as exhibited below:

<input type="file" @change="previewImage" accept="image/*">

The previewImage method receives the event parameter, which incorporates event.target - the necessary DOM element for input. Subsequently, your previewImage method can proceed to read the image file in a standard fashion:

previewImage: function(event) {
    // Reference to the DOM input element
    var input = event.target;
    // Verify the existence of a file prior to attempting to read it
    if (input.files && input.files[0]) {
        // create a new FileReader instance to interpret the image and convert it into base64 format
        var reader = new FileReader();
        // etc...

Feel free to consult this jsFiddle for guidance and maintain an open inquiry so that individuals proficient in haml and typescript may present a more targeted response.

Answer №2

The issue appears to be stemming from a particular line within your page_image.haml file.

%img(src="image" name="image")

If this translates or compiles to

<image src="image" name="image">
, then it's likely that your browser is trying to locate the image at localhost:8080/image instead of displaying it from data.image within the Vue component.

As I mentioned in a previous response, since I'm not familiar with haml, you'll need to find a solution on your own.

Edit:

Based on the other haml code provided in your query, have you tried using this syntax?

%img(v-bind:src="image" name="image")

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

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

`Optimizing Django by using multiple room relationships to save formset related models`

I need help with saving a formset that involves two models in a many-to-many relationship. When I open the page, two forms are displayed but after filling them out and clicking "Add", the fields for "phone" and "client_name" get cleared and the form is not ...

Exploring unique v-ifs in Vue.js based on a prior selection

I'm having trouble showing different divs based on select options. Even though I have set up v-if conditions for both "de" and "fr", only the first one is being displayed when "fr" is selected. Any idea what's causing this issue? I can't se ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Order JSON object based on designated Array

I'm looking to organize a JSON object in a specific order, Here is the current object structure: { "you": 100, "me": 75, "foo": 116, "bar": 15 } I would like to rearrange this object in the following sequence ['me', 'foo', &apos ...

What is the process for integrating real HTML into my code using Vue?

I'm in the process of developing a deck editor using Vue and I would like to include a list of cards with an "Add" button on each one. Upon clicking the button, I want the card's image and name to show up in a side bar. However, when concatenati ...

Tips for showing the value in the subsequent stage of a multi-step form

Assistance is required for the query below: Is there a way to display the input field value from one step to the next in multistep forms? Similar to how Microsoft login shows the email in the next step as depicted in the image below: ...

Mastering the Art of Live Search in Drop Down Multi Select

I need to develop a search functionality similar to the one found on . This search should allow users to select options from a dropdown menu or type their own search query, and provide live search results. I attempted to use the jQuery plugin https://www.j ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

What is the best way to showcase this information within my columns?

I'm facing an issue with VueJS. I have a large dataset that I want to display in columns in a specific order. How can I properly insert the code for this? Thank you for any assistance. [ { "sort": 0, "title": "My title", "description": ...

When placing the script URL with a pound sign into the DOM, it gets truncated

When I receive URLs for trackers from an external resource, they often contain a # symbol which causes the URL to be cut off after the pound sign when trying to execute/load it in the DOM. Unfortunately, these URLs are provided by a 3rd party and I have no ...

Looking to execute multiple programs simultaneously within the prestart script in the package.json file, and bypass any exit error codes

I need to run yarn tsc and yarn lint during every yarn start to identify any code errors. This is how my scripts property is set up: "scripts": { "start": "expo start", "android": "expo start --android" ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...

Revitalizing HTML and Google Maps with AJAX, PHP, and JQuery

Context: I am currently working on a project that involves integrating a Simple Google Map with an HTML form right below it. The form collects user input and upon submission, sends the data via AJAX to a PHP script for processing API calls and generating i ...

Discover the country's three-letter code with the power of HTML and Javascript!

I am in search of a way to determine the location of a user based on the country they are browsing from. I want to achieve this using HTML and Javascript. While researching on stackoverflow, I came across various suggestions to use different API's for ...

AngularJS's hidden input field is not being properly updated

I am currently using angularjs v1.0.7 and facing an issue with a hidden form field whose value is related to another input value. In the example provided at http://jsfiddle.net/4ANaK/, the hidden field does not update as I type in the text input field. &l ...

Selenium Webdriver failing to select menuitem using text, xpath, or ID

Currently, I have some HTML code embedded in a SharePoint page that appears as follows: <span style="display:none"> <menu type='ServerMenu' id="zz28_RptControls" largeIconMode="true"> <ie:menuitem id="zz29_AddColumn" type="optio ...