Site icon RemoteStack

Vue 2 Image Upload and Image Preview Tutorial

Vue js image preview tutorial; Through this tutorial, we are going to teach you one more feature, which is primarily seen in web apps. We will explain how to show image preview after upload in the Vue js application using the subtle FileReader API.

Showing your site visitors image preview after selecting image files from the system is a good strategy.

It lets them know what they are uploading; in this quest, FileReader API could be helpful to us; it provides eloquent ways to read the file object and provides significant ways to deal with image files.

FileReader is a JavaScript API, which allows reading the contents of File or Blob asynchronously. You can read single or multiple files at once using the pragmatic event handlers provided by this API.

Here is the roadmap for this Vue image upload with a preview guide; we will create a basic app, create a file upload vue component, and most importantly, create a custom method to choose or select files from the device memory and show image upload preview in vue.

Swift Vue Image File Upload Preview Example

Let start implementing image preview in vue before it is uploaded.

Setup Vue Environment

If you haven’t configured the Vue command line interface, go for it with the below command.

npm install -g @vue/cli

# or

yarn global add @vue/cli

Install Vue Js App

Creating a new vue project requires executing the suggested command, though you may name the project anything you want.

vue create vue-social-conflux

Make sure to get inside the project.

cd vue-social-conflux

Vue Gatsby Error

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Fix Multi Word Error

In order to fix multi-word error, insert the given code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

Install and Register Bootstrap Package

This step is optional; you can completely skip it but if you want to design persuasive user interface elements in very little time, then add the Bootstrap package into the vue app.

npm install bootstrap

Next, add the css path in the src/main.js file.

import Vue from 'vue'
import App from './App.vue'

// import Bootstrap
import 'bootstrap/dist/css/bootstrap.css'

new Vue({
  render: h => h(App),
}).$mount('#app')

Create Vue Component

The component is a reusable block of code that helps in using the same functionality repeatedly; consequently, we need to create a FileUpload.vue file in the components folder, after that place the following code in the file new component.

<template>

</template>
 
<script>

export default {
  name: "App",
  data() {
    return {
    };
  }
};
</script>

Next, register the new component in the src/App.vue file.

<template>
  <div class="container mt-5 text-center">
    <FileUpload />
  </div>
</template>

<script>
import FileUpload from './components/FileUpload.vue'

export default {
  name: 'App',
  components: {
    FileUpload
  }
}
</script>

Display Image Upload Preview in Vue

Head over to the src/components/FileUpload.vue and update the following code in the file to view the image preview in vue.

<template>
    <div class="container">
        <div
          class="previewBlock"
          @click="chooseFile"
          :style="{ 'background-image': `url(${filePreview})` }">
        </div>

        <div>
          <input
            class="form-control form-control-lg"
            ref="fileInput"
            type="file"
            id="formFileLg"
            @input="selectImgFile">
        </div>
    </div>
</template>

<script>
    export default {
      data() {
          return {
            filePreview: null
          };
        },
      methods: {
          chooseFile () {
              this.$refs.fileInput.click()
          },
          selectImgFile () {
            let fileInput = this.$refs.fileInput
            let imgFile = fileInput.files

            if (imgFile && imgFile[0]) {
              let reader = new FileReader
              reader.onload = e => {
                this.filePreview = e.target.result
              }
              reader.readAsDataURL(imgFile[0])
              this.$emit('fileInput', imgFile[0])
            }
          }
      }
    }
</script>

<style scoped lang="css">
    .container {
        max-width: 600px;
    }
    .previewBlock {
        display: block;
        cursor: pointer;
        width: 300px;
        height: 280px;        
        margin: 0 auto 20px;
        background-position: center center;
        background-size: cover;
    }
</style>

We created a component and put two elements, and one UI element is div which shows the image preview; we are setting up the background image to show the image preview; we also attached the click event if somebody clicks on it, then the file picker will be invoked for image selection.

On the other hand, we added the file input element with the selectImgFile() method; this method uses the FileReader object to build the image preview feature in vue.

Start Vue Project

Now, start the vue app with the given below command; you may use the url to open the app on the browser.

npm run serve
http://localhost:8080

Conclusion

We are displaying a preview of an image upload in vue, and now you can show your site visitors a preview of the image they want to upload to the server. We created a simple image upload component, in which a user can choose an image file and display the preview of the selected file using the FileReader API.

Exit mobile version