What is the best way to add an image in a Vue.js project?

Here is the code snippet from the script section of my Vue component:

While I am able to get all the input field values correctly, the image and video uploads are displaying empty values.

Despite my attempts to address this issue, I have been unsuccessful so far.

        playVideo(url) {
            let video = $('#video-preview').get(0);
            video.preload = 'metadata';
            // Load video in Safari / IE11
            if (url) {
                video.muted = false;
                video.playsInline = true;
                video.play();
            }
        },

        // Read a file input as a data URL.
        readDataUrl(input, callback) {
            if (input.files && input.files[0]) {
                let fileReader = new FileReader();
                fileReader.onload = function () {
                    callback(fileReader.result);
                };
                fileReader.readAsDataURL(input.files[0]);
            }
            else {
                callback(null);
            }
        },

        // Read a file input as an object url.
        readObjectUrl(input, callback) {
            if (input.files && input.files[0]) {
                let fileReader = new FileReader();
                fileReader.onload = function () {
                    let blob = new Blob([fileReader.result], {type: input.files[0].type});
                    let url = URL.createObjectURL(blob);
                    callback(url, blob);
                };
                fileReader.readAsArrayBuffer(input.files[0]);
            }
            else {
                callback(null);
            }

        },

    }

}

I am aiming to upload an image and video file, preview them, and save them as blobs.

https://i.sstatic.net/urLLw.jpg

The screenshot above highlights my response to @samayo

However, I am encountering issues with the image and video blobs appearing as empty values.

Answer №1

It seems that in this situation, you may be seeking a solution along the lines of the following:

For instance: uploading an image and previewing it prior to submission

<template>
   <div>
      <img src:"previewImage" class="uploaded-image" />
      <input type="file" accept="image/jpeg" @change=uploadImage>
   </div>
</template>

<script>
    export default {
        name:'imageUpload',
        data(){
            return{
               previewImage:null
            }
        },
        methods:{
            uploadImage(e){
                const image = e.target.files[0];
                const reader = new FileReader();
                reader.readAsDataURL(image);
                reader.onload = e =>{
                    this.previewImage = e.target.result;
                    console.log(this.previewImage);
                };
            }
        }
     }  // added missing closure
</script>



<style>
   .uploaded-image{
     display:flex;
   }
 </style>

Answer №2

If you are utilizing the power of axios or fetch to upload files in combination with vue, the process is quite straightforward.

This excerpt is taken directly from my ongoing project where I employ axios for image uploads:

First and foremost, ensure that your input field resembles the following:

<input type="file" accept="image/*" @change="uploadImage($event)" id="file-input">

Next, implement a method similar to the one below:

methods: {

  uploadImage(event) {

    const URL = 'http://foobar.com/upload'; 

    let data = new FormData();
    data.append('name', 'my-picture');
    data.append('file', event.target.files[0]); 

    let config = {
      header : {
        'Content-Type' : 'image/png'
      }
    }

    axios.put(
      URL, 
      data,
      config
    ).then(
      response => {
        console.log('image upload response > ', response)
      }
    )
  }
}

Answer №3

If you're looking to upload an image and preview it prior to submission, there is a simple and effective method available.

<template>
  <input type="file" accept="image/*" @change="onChange" />
  <div id="preview">
    <img v-if="item.imageUrl" :src="item.imageUrl" />
  </div>
</template>


<script>
export default {
  name: 'imageUpload',
  data() {
    return {
      item:{
          //...
          image : null,
          imageUrl: null
      }
    }
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0]
      this.image = file
      this.item.imageUrl = URL.createObjectURL(file)
    }
  }
} 
</script>

Answer №4

Combining insights from various people, here is a summary.

this.image is encoded in base64 format and can be sent to your API seamlessly.

<template>
    <v-file-input
       v-model="file"
       chips
       accept="image/*"
       label="Image"
       @change="onFileChange"
    />
</template>

<script>
export default {
    data: { file: null, image: null },
    methods: {
        onFileChange() {
            const reader = new FileReader()
            reader.readAsDataURL(this.file)
            reader.onload = e => {
                this.image = e.target.result
                console.log(this.image)
            }
        },
    },
}
</script>

Answer №5

Combine all elements to view and execute the upload process, remembering to update the URL with your server's destination.

<template>
    <div>
        <img src:"previewImage" class="uploading-image" />
        <input type="file" accept="image/jpeg" @change=uploadImage>
    </div>
</template>

<script>
    export default {
        name:'imageUpload', 
        data(){
            return{
                previewImage:null
            }
        },
        methods:{
            uploadImage(e){
                const image = e.target.files[0];
                const reader = new FileReader();
                reader.readAsDataURL(image);
                reader.onload = e =>{
                    this.previewImage = e.target.result;
                    console.log(this.previewImage);
                };
                
                const URL = 'http://example.com/upload'; 

                let data = new FormData();
                data.append('name', 'my-picture');
                data.append('file', e.target.files[0]); 

                let config = {
                    header : {
                        'Content-Type' : 'image/png'
                    }
                }

                axios.put(URL,data,config).then(response => {
                    console.log('image upload response > ', response)
                })
            }

        }
    } 
</script>

<style>
    .uploading-image{display:flex;}
</style>

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

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...

Is passportjs responsible for managing user registration?

Is it possible to utilize Passport for user signup if I am storing user information on a self-hosted server and cannot find a user signup function in the Passport.js documentation? ...

The lookAt function in threeJS seems to be pointing in the opposite direction due to inherited rotations

I'm attempting to align this._mesh.skeleton.bones[ 5 ] (located at the bend in the green object extending from the hand) with the yellow helper line. _FindBubble() { const handPosition2world = new THREE.Vector3(); this._anchor[&apo ...

Running a repeated script

I recently discovered a fantastic script called Typer that creates a typewriter effect. However, I noticed that it does not have a built-in method to loop the animation once it reaches the end. Does anyone have any suggestions on how to achieve this? t ...

Tips for modifying an array in initstate value with the help of useState

Struggling to update the categories array's value or insert categories json data into it after fetching from the database. Need help finding the correct way to do this. Note: Make sure to review the loadCategories function. import React, {useEffect, u ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...

AngularJS: Error encountered when trying to assign a value to a read-only property in the ng-submit directive

I've been working on a personal project to practice angularJS, but I've encountered a problem that seems unsolvable to me. The issue arises when I try to utilize the submitLogin() function in my LoginCtrl.js file upon form submission. An error m ...

Steps to Incorporate Chunk into Laravel's Query Builder

When dealing with large records in my Database, how can I write Chunks in this query? $users = DB::table('products')->orderBy($sortbysql, $sortbysqltype) ->where('product_name', 'like', '%' . $keyword . &apo ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

What is the syntax for implementing the 'slice' function in React?

While working on my React app, I encountered an issue when trying to extract the first 5 characters from a string using slice. The error message displayed was: TypeError: Cannot read property 'slice' of undefined I am utilizing a functional compo ...

Troubleshooting issues with the 'date' input type feature on mobile devices

When I use the following code: <input type='month' ng-readonly='vm.isReadonly' required min="{{vm.threeMonthsAgo}}" max='{{vm.oneMonthAhead}}'/> I am experiencing some difficulties on mobile devices that do not occur o ...

Determine the fill color attribute value of a rectangle using Testcafe paired with typescript

Here is a code snippet I need help with: <colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www. ...

Oops! The program encountered an error where it cannot assign a value to the 'id' property of an undefined object while trying to store a session in redis

I am currently working on an Angular4 login application and I am looking to store sessions in Redis. To accomplish this, I am utilizing Express session. However, I have encountered the following error: req.session.id = userName; ...

Tips for incorporating JavaScript into your Selenium WebDriver workflow using Java

Looking to integrate JavaScript with WebDriver (Selenium 2) using Java. After following a guide listed on the Getting Started page, I found an initial instruction to run: $ ./go webdriverjs Curious about the specific folder/location where the above ...

Efficiently expanding and collapsing multiple levels with Bootstrap through AJAX data responses using jQuery

Looking for help with creating a multi-level expand-collapse feature using JSON data response with jQuery AJAX. As I am new to AJAX, I would appreciate any assistance with implementing the JSON data and expand-collapse plugin. All the data for different l ...

Tips for combining several JSON objects in a Node.js/Jade merge operation

Given the code below which sets up various configurations for a company: default.js (utilized by config.js to load base configurations) { "templateData": { "corp": { "corpName": "Company", "DepartmentOne": { "name": "Dep ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Is there a way to conceal JavaScript code?

I am trying to keep my AJAX code hidden from users who view the source of my PHP page. How can I achieve this? Below is the AJAX code that I currently have: <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=n ...

What is the best way to retrieve elements from this JSON data?

Currently, I am developing a command line interface to display random quotes. I have found an API to fetch quotes from, but the issue is that the JSON response is returned as an array. [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate ...

Trouble with attaching a click event to a jQuery datepicker

I am attempting to attach a click event to .ui-state-default after a jQuery datepicker has been displayed (I do not have access to the html generating the datepicker so I cannot utilize any datepicker-specific events) and it functions properly using $.bind ...