Vuetify image upload with preview example - BezCoder (2023)

In this tutorial, I will show you how to use Vuetify to create an uploaded image with a preview sampleSharesImulti-partFile for sending HTTP requests. You'll also learn how to add a progress bar, view a response, and list the image information (with URL).

More practice:
Example of uploading multiple images via Vetify
An example of a Vuetify data table with the CRUD | application v data table
Vue.js JWT authentication with Vuex and Vue Router

Use Bootstrap:

Contents

  • overview
  • Technology
  • Set up a Vuetify image upload project
  • Project structure
  • Initialize Axios for the HTTP client to upload Vuetify images
  • Create an image upload service
  • Create an image upload component
  • Add an Upload Image component to an application component
  • Configure the port for the Vuetify image uploader
  • Launch the application
  • further reading
  • Diploma
  • Source code

overview

We will create a Vuetify image upload with a preview application so that the user can:

  • see upload process (in percent)
  • View all uploaded images
  • Link to the file after clicking on the name of the image

Vuetify image upload with preview example - BezCoder (1)

Here are the APIs that Axios will use to send HTTP requests:

methodsURLsactions
POST/uploadUpload file
RECEIVE/ActDownload list of files (name and URL)
RECEIVE/files/[file name]download file

For information about rest APIs server implementation, see one of the following posts:
Example of the Node.js Express File Upload Rest API
Uploading a Node.js Express file to MongoDB - example
An example of expressly uploading a Node.js file to Google Cloud Storage
An example of uploading a multipart Spring Boot file (into a static folder).
An example of uploading a Spring Boot file to the database

Technology

  • Version 2.6
  • axes 0.21.1
  • Vuetify 2

Set up a Vuetify image upload project

Open cmd in the folder where you want to save the project folder and run the following command:
vue creates vuetify-image-upload-preview

You will see several options, please selectStandard (babel, eslint).

(Video) Uploading Images & Videos in Vue.js with the Cloudinary Upload Widget - Dev Hints

After successfully creating the Vue project, we import Vuetify with the following command:add vuetify view.
The console shows the following information:

�📦 Installation with vue-cli-plugin-vuetify...+[email protected]Added 5 packages from 7 contributors and checked 1277 packages out of 25013. 0 vulnerabilities found ✔ Plugin successfully installed: vue-cli-plugin-vuetify? Select preset: Default (recommended)� 🚀 Call generator for vue-cli-plugin-vuetify...� 📦 Install additional dependencies... Added 7 packages from 5 contributors and checked 1284 packages out of 41,183. 0 vulnerabilities found⚓ Running completion hooks... ✔ Successfully invoked plugin generator: vue-cli-plugin-vuetify Updated/added the following files: src/assets/logo.svg src/plugins/vuetify.js vue.config.js bundle-lock.json bundle. json public/index.html src/App.vue src/components/HelloWorld.vue src/main.js

openPlugins/vuetify.js, You can see:

import Vue from "vue"; import Vuetify from "vuetify/lib"; Vue.use (Vuetify); export default new Vuetify({});

then inmain.jsfile, the Vuetify object is automatically added to the Vue app:

import Vue from "vue" import app from "./App.vue" import vuetify from "./plugins/vuetify"; Vue.config.productionTip = falsenew Vue({ vuetify, render: h => h(App)}) .$mount('#application')

Iview.config.js:

module.exports = { transpileDependencies: ["vuetify"]};

Project structure

Let's delete unnecessary folders and files and then create new ones as follows:

Vuetify image upload with preview example - BezCoder (2)

Let me explain briefly.

Plugins/vuetify.jsImports the Vuetify library, initializes and exports the Vuetify object formain.js.
Thanks to the command, we don't have to do anything with these two filesAdd Vuetifythey helped us

UploadFilesServiceProvides methods for storing files and retrieving files using Axios.
Upload imageThe component contains a form for uploading images, a progress bar and a list of displayed images.
app. vueis the container where we embed all Vue components.

http-common.jsInitializes Axios with the base HTTP URL and headers.
- We configure dependencies and transpile ports for our application inview.config.js

Initialize Axios for the HTTP client to upload Vuetify images

Now let's add the Axios library with the command:Install npm axios.

Podsourcethe folder we createhttp-common.jsfile as follows:

import axios z „axios”;export default axios.create({ baseURL: „http://localhost:8080”, headers: { „Content-type“: „application/json“ }});

Remember to change thembaseURL, it depends on the REST API URL configured on the server.

(Video) 15 Laravel and Vue js Image Upload with image preview

Create an image upload service

This service uses Axios to send HTTP requests.
There are 2 functions:

  • file upload): POST form data with a callback to track upload progress
  • download files(): Get the image information list

Services/UploadFilesService.js

import http from "../http-common"; class UploadFilesService { upload(file, onUploadProgress) { let formData = new FormData(); formData.append("file", file); return http.post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" }, onUploadProgress }); } getFiles() { return http.get("/files"); }} export default new service UploadFilesService();

– First we import Axios ashttpapart fromhttp-common.js.

create datais a data structure that can be used to store key-value pairs. We use it to create an object corresponding to an HTML formto add()Method.

- We doonUploadProgressreveal the progress of events. These progress events are expensive (change detection for each event) so you should only use them if you want to monitor them.

- We call themPost()&receive()methodSharesto send an HTTP POST & Get request to the file upload server.

Create an image upload component

Let's create an image upload UI with progress bar, button and Vuetify notification. We also have groups of tab and list items for viewing uploaded files.

First, let's create a Vue component template and import itUploadFilesService:

ingredients/Upload an image. vue

Then we define some variables in itDane()

export default { name: "upload-image", data() { return { currentImage: undefined, thumbnail: undefined, progress: 0, message: "", imageInfos: [] }; },};
  • Image informationis an array{Name, URL}objects. We will display his data in VuetifyV-sheetsIin-list-item-group.
  • Progressis the percentage of image upload progress.

Next we defineselect photo()A method that will help us get the selected imagev input fileInsert the element later in the HTML template.

export default { name: "upload-image", ... Metody: { selectImage(image) { this.currentImage = image; this.previewImage = URL.createObjectURL(this.currentImage); ten.postęp = 0; ta.wiadomość = ""; }, }};

We access currentImage as an input parameterBild. Then we'll callUploadService.upload()method nacurrent photowith callback.

We also useURL.createObjectURL()static method to get image preview url asThumbnail. This method createsDOMStringincluding the URL describing the object provided in the parameter. The life of the URL is tied to the document in the window where it was created.

(Video) Vue Image Upload Made Easy

We also specifyupload()way as follows:

export default { name: "upload-image", ... Metody: { ... upload() { if (!this.currentImage) { this.message = "Proszę wybrać obraz!"; wracać; } ten.postęp = 0; UploadService.upload(this.currentImage, (event) => { this.progress = Math.round((100 * event.loaded) / event.total); }).then((response) => { this.message = Response.data.message; return UploadService.getFiles(); }).then((images) => { this.imageInfos = images.data; }).catch((err) => { this.progress = 0; this .message = „Nie można przesłać obrazu!” + err; this.currentImage = undefined; }); }, }, };

We check ifcurrent photois here or not. Then we'll callUploadService.upload()method nacurrent photowith callback.

TheProgressis calculated on this basisloaded eventIevent.total.
We'll call you when the transfer is completeUploadService.getFiles()to fetch information about the images and assign the resultImage informationArray.

We have to do this work toohandle()Method:

export default { name: "upload-image", ... mount() { UploadService.getFiles().then(response => { this.imageInfos = Response.data; }); }};

Now let's implement the UI HTML template to upload images using Vuetify. Add the following content:

In the code above, we useVuetify Linear Progression:v-progress-linear. This component responds to user input withModel V. We bind themProgressThe model (percentage) to display in the progress bar.

Thev-btnis called a buttonupload()method, then you will get a notification fromAlarm V.

A preview of the uploaded image will be displayed:

Add an Upload Image component to an application component

openapp. vueand embed themUpload imageingredient withSign.

(Video) Vue Image Upload Made Easy with axios and web api.

Configure the port for the Vuetify image uploader

Because most HTTP servers use a CORS configuration that accepts resource sharing limited to certain sites or ports. So you need to configure the port for our application.

Changeview.config.jsfile by addingdevServer:

module.exports = {transpileDependencies: ["vuetify"], devServer: {port: 8081,},};

We launched our application on the port8081.view.config.jswill be loaded automatically by@vue/cli-service.

Launch the application

First, you need to start one of the following REST API servers:
Example of the Node.js Express File Upload Rest API
Uploading a Node.js Express file to MongoDB - example
An example of expressly uploading a Node.js file to Google Cloud Storage
An example of uploading a multipart Spring Boot file (into a static folder).
An example of uploading a multipart Spring Boot file (to the database).

Start the Vue image upload with the preview app with the following command:
npm start server.

Open a browser with the URLhttp://localhost:8081/and check the result.

further reading

If you want to build a Vuetify CRUD app as follows:

Vuetify image upload with preview example - BezCoder (3)

You can visit the tutorial:
An example of a Vuetify data table with the CRUD | application v data table

Diploma

Today we learned how to create a Vue/Vuetify example of uploading photos with a preview using Axios. We also provide the ability to view the list of photos, the upload progress bar and the list of photos uploaded from the server.

For information about rest APIs server implementation, see one of the following posts:
Example of the Node.js Express File Upload Rest API
Uploading a Node.js Express file to MongoDB - example
An example of expressly uploading a Node.js file to Google Cloud Storage
An example of uploading a multipart Spring Boot file (into a static folder).
An example of uploading a multipart Spring Boot file (to the database).

If you want to upload multiple images at once:

(Video) Inferno #22: Simple image upload preview component in Vuejs

Vuetify image upload with preview example - BezCoder (4)

please visit:Example of uploading multiple images via Vetify

Source code

Vue/Vuetify client source code is uploadedGithub.

FAQs

How do I upload files to Vue? ›

Once the user has selected a file, you can upload the JavaScript blob by adding it to a FormData instance. Below is an example. const app = new Vue({ data: () => ({images: null}), template: ` <div> <input type="file" @change="uploadFile" ref="file"> <button @click="submitFile">Upload!

How do I add an image to preview in HTML? ›

Add a div element with a class named image-preview-container . Inside it, add another div element with a class named preview . This element will contain an img tag with an ID named preview-selected-image . This will be used to show the preview of the selected image.

How do I preview an image before uploading in Vue? ›

So here's how the workflow would be:
  1. The user clicks on . base-image-input .
  2. We call click() on <input type="file"> to open up the file picker.
  3. Once the user selects an image, we listen for @input on <input type="file"> , read that file, and then display it as background-image for . base-image-input .

How to add image upload in Angular? ›

Angular Image Uploader Tutorial In 2022
  1. 1 Browse File Upload.
  2. 2 User Interface Creation.
  3. 3 Backend Angular HTTP Client File Upload.
  4. 4 Displaying Progress Indicators While Uploading A File.
  5. 5 File Upload Cancellation.
  6. 6 Accepting Specified File Types.
  7. 7 Uploading Multiple Files Through Angular Image Uploader.
Sep 29, 2022

How to upload image file in Angular JS? ›

HTML
  1. <div ng-app="plunkr">
  2. <div ng-controller="UploadController ">
  3. <form>
  4. <input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
  5. <!-- < input type="file" ng-file-select="onFileSelect($files)" multiple> -->
  6. </form>
  7. <img ng-src="{{imageSrc}}" />

How do I add an image to a PDF in Vue? ›

Click the Custom Stamp button. The file explorer dialog will appear, choose the image, and then add the image to the PDF page. Note: The JPG and JPEG image format are only supported in custom stamp annotations.

How do I upload multiple images to Vue? ›

Setup
  1. 1 – Import the vue component locally in the script Tag. <script> import { VueMultiImageUpload } from '@zakerxa/vue-multiple-image-upload'; export default { components:{ VueMultiImageUpload } } </script>
  2. 2 – In your Vue Template.
Oct 11, 2022

How do I upload a Vue JS project to a server? ›

Deploy your application using nginx inside of a docker container.
  1. Install docker.
  2. Create a Dockerfile file in the root of your project. ...
  3. Create a .dockerignore file in the root of your project. ...
  4. Create a nginx.conf file in the root of your project. ...
  5. Build your docker image. ...
  6. Run your docker image.
Nov 8, 2022

What is image Preview? ›

A thumbnail also means a small and approximate version of a full-size image or brochure layout as a preliminary design step. This is also referred to as a preview image and is a smaller version of the original image.

How do I export selected images in Preview? ›

Double-click on the selected images to open Preview. You can also right-click the selected images and click Open With to choose Preview. Click Edit from the top menu bar and choose Select All. Then click File > Export Selected Images.

How to display image in HTML with example? ›

Chapter Summary
  1. Use the HTML <img> element to define an image.
  2. Use the HTML src attribute to define the URL of the image.
  3. Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed.

How do I preview a file in HTML? ›

You can preview any HTML file in your web browser. Go to the file in question, right-click on the file, select “Open with,” then select your browser, whether that's Google Chrome, Firefox, Safari, Edge, or other.

How do you preview content in HTML? ›

HTML Previews can be presented either using the HTML Preview action step or in script using the HTMLPreview object. By default, previews are presented in a window, and contain toolbars with buttons to “Continue” or “Cancel”.

How to display image preview in Angular? ›

To show the image preview in Angular, we declared the img HTML tag and bind the src tag to the variable. We will assign the image URL to the src variable using the new FileReader() method.

How to upload a file and view it in Angular? ›

In this post, we will cover the following topics:
  1. How to upload files in a browser.
  2. Building the user interface of a file upload component.
  3. Selecting a file from the file system using a file upload dialog.
  4. Uploading a file to the backend using the Angular HTTP Client.
  5. How to display a file upload progress indicator.
Jan 20, 2023

How to upload and preview of PDF file in Angular? ›

The blog sections will help you understand how to create an Angular application and integrate the GcPdfViewer control:
  1. Integrate the GrapeCity Documents PDF Viewer Control into the Angular Project.
  2. Load or Open a Default PDF Template.
  3. Load or Open a PDF File from a URL.
  4. Load or Open a PDF File from Another Domain URL.
Jul 26, 2022

How to import a image in Angular? ›

Getting Startedlink
  1. Step 1: Import NgOptimizedImagelink. content_copy import { NgOptimizedImage } from '@angular/common' ...
  2. Step 2: (Optional) Set up a Loaderlink. ...
  3. Step 3: Enable the directivelink. ...
  4. Step 4: Mark images as priority link. ...
  5. Step 5: Include Height and Widthlink.

How do I display images in angular using local image path? ›

You have two options:
  1. Place images into servlet container web folder and then they will be available automatically as resources. In Angular you will refer to images using relative path to application root. ...
  2. Implement REST action in Spring controller which will provide image data.
Oct 4, 2018

How do I show Preview of uploaded image in react? ›

In the browser environment, clients can initiate image upload by browsing files using an input element or the drag and drop API. You can then use the URL API or the FileReader API to read the image files and preview them.

How do I Preview a PNG file? ›

Right-click on an image file and you should now see an Image Preview command in the popup menu. Click that command to view the image in Windows Photo Viewer (Figure D). Photo Viewer instantly pops up. Click the magnifying glass icon and move the slider to zoom in or out of the image.

How to upload image and post in API in Angular? ›

Use the Angular CLI command ng g cl to create a new class that represents a file to upload. You can create a folder named file-upload at the same time you create the FileToUpload class. The FileToUpload class will be created in this new folder. Open the newly generated file-to-upload.

How to upload image using Angular JS? ›

JS
  1. var app = angular. module('plunkr', [])
  2. app. controller('UploadController', function($scope, fileReader) {
  3. $scope. imageSrc = "";
  4. $scope.$ on("fileProgress", function(e, progress) {
  5. $scope. progress = progress. loaded / progress. total;
  6. });

How to preview the file in Angular? ›

Dependencies
  1. import { Component } from '@angular/core';
  2. name = 'Angular 4'; url = '';
  3. onSelectFile(event) { if (event. target. ...
  4. files[0]) { var reader = new FileReader();
  5. reader. readAsDataURL(event. target. ...
  6. [0]); // read file as data url.
  7. reader. onload = (event) => { // called. ...
  8. this. url = event.

How do I add a file to Preview? ›

Open the Options menu in Windows File Explorer and select the View tab. Under the View tab, you will see a list of Advanced settings. Ensure that Show preview handlers in preview pane has a check next to it in order for the preview pane to display.

How to show PDF as an image in Angular? ›

Follow these steps to convert PDF to Image in Angular 11.
  1. Create Angular application. ...
  2. Run Angular application. ...
  3. Install bootstrap. ...
  4. Install ng2-pdf-viewer package. ...
  5. Uploading PDF. ...
  6. Display pdf in the browser. ...
  7. Previous and Next page. ...
  8. Install html2canvas, cropperjs, and jquery.
Jul 9, 2021

How do I insert a picture into a PDF in Preview? ›

When Preview opens, press Command+A on your keyboard to select the entire image. Next, press Command+C to copy the image. Now, bear with us: This may seem strange, but it works. Press Command+V to paste the image, and the new copy of your image will cover the original image.

How to load images fast in Angular? ›

Follow the below steps to increase image loading speed in Angular applications.
  1. Step 1: Import NgOptimizedImage directive in AppModule. ...
  2. Step 2: Replace image src attribute with rawSrc. ...
  3. Step 3: Set width and height attributes. ...
  4. Step 4: Configure loader of image CDNs. ...
  5. Step 5: preconnect image Url.
Sep 1, 2022

How do I import image? ›

Import photos and videos
  1. Use a USB cable to connect your device to the PC.
  2. In the search box on the taskbar, type photos and then select the Photos app from the results.
  3. Select Import from the app bar.
  4. Your devices will automatically show under Import.
  5. Choose your device from the list of connected devices.

How to upload image using form data in Angular? ›

  1. Step 1 – Initializing your Angular 13 Project & Creating the Bare-Bones Artifacts. ...
  2. Step 2 – Importing HttpClientModule. ...
  3. Step 3 – Adding Bootstrap 4. ...
  4. Step 4 – Implementing the Angular 13 Multiple File Upload Service. ...
  5. Step 5 – Creating our Angular 13 UI for Upload Multiple Files. ...
  6. Step 6 – Running your Angular 13 App.
Feb 25, 2021

Videos

1. Nodejs Image Upload using Multer | Nodejs and Expressjs and MongoDB
(Sahul Hameed)
2. Multiple Image Upload in Vuejs
(360learntocode)
3. Uploading Multiple Images with Laravel and Filepond: A Step-by-Step Tutorial
(Code With Tony)
4. Uploading Images with Multer | NodeJS and ExpressJS
(PedroTech)
5. How to Upload Image in Laravel 7 using Vuejs
(Edwin Encomienda)
6. Image / File Upload On Node Sequelize Rest API and React implementation Complete Guide 🔥🔥
(Great Adib)

References

Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated: 09/16/2023

Views: 5401

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.