• Stars
    star
    221
  • Rank 178,954 (Top 4 %)
  • Language
    JavaScript
  • Created over 7 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple and hackable file uploader for VueJs. Supports Vue >= 2.1

Introduction

Vue clip is a minimalistic and hackable file uploader for VueJs. I wrote this plugin due to the absence of well written file uploaders with fine-grained controls.

Version Build Status Downloads License

Features

  1. Written in vanilla Javascript.
  2. Weighs 17.9KB ( Minified and Gzip ), 57KB ( Minified ).
  3. Hackable to the core with custom events.
  4. Does not pollute DOM by adding unnecessary markup. Infact the component will create a single div element.

Quick Intro

<iframe src="https://www.youtube.com/embed/84_SwbPWjKo" type="text/html" width="640" height="360" frameborder="0"></iframe>

Setup

You can make use of module by installing it from npm or directly using it from CDN.

Npm

npm i --save vue-clip
import Vue from 'vue'
import VueClip from 'vue-clip'

Vue.use(VueClip)

Globally

Also, you can reference the script file via CDN which will add a global component called vue-clip to the Vue instance.

Basic Usage

<template>
  <vue-clip :options="options">
    <template slot="clip-uploader-action">
      <div>
        <div class="dz-message"><h2> Click or Drag and Drop files here upload </h2></div>
      </div>
    </template>

    <template slot="clip-uploader-body" scope="props">
      <div v-for="file in props.files">
        <img v-bind:src="file.dataUrl" />
        {{ file.name }} {{ file.status }}
      </div>
    </template>

  </vue-clip>
</template>

<script>
  export default {

    data () {
      return {
        options: {
          url: '/upload',
          paramName: 'file'
        }
      }
    }

  }
</script>

Configuration Options

Option Possible Values Description
url String, Function Url to be used for uploading files. This can be a string or a function ( in case your URL is dynamic )
method String, Function Http method to be used. Defaults to post.
parallelUploads Number Number of files to be uploaded in parallel.
maxFilesize Number, Object The file size in MB to be allowed. Also, you can pass an object with limit and error message.
paramName String Param name to be used for uploading file(s). Defaults to file.
uploadMultiple Boolean Whether or not to upload multiple files.
headers Object Http headers to be sent along each request.
maxFiles Number, Object a maximum number of files to be uploaded. You can also pass an object with limit and error message.
acceptedFiles Array, Object File types to be accepted. ['image/*', 'application/pdf'].
accept Function A custom function to be used for validating each file upload. This method receives a done callback. In the case of any errors, you must call done with a single error argument.

maxFilesize

The maxFilesize option defines the size of the file to be checked for when uploading files.

{
  maxFilesize: 1 // 1mb
}

// or

{
  maxFilesize: {
    limit: 1,
    message: '{{ filesize }} is greater than the {{ maxFilesize }}'
  }
}

maxFiles

The maxFiles option defines the maximum number of files to be uploaded.

{
  maxFiles: 5
}

// or

{
  maxFiles: {
    limit: 5,
    message: 'You can only upload a max of 5 files'
  }
}

acceptedFiles

The acceptedFiles option defines the mime types of files to be accepted.

// as an array of mime types

{
  acceptedFiles: ['image/*', 'application/pdf']
}

// as an object with an array of mime types
// and a custom error message

{
  acceptedFiles: {
    extensions: ['image/*'],
    message: 'You are uploading an invalid file'
  }
}

// as a plain, comma-delimited string

{
  acceptedFiles: 'image/*,application/pdf'
}

accept

The accept is a low-level method to run manual validations and return a formatted error string ( in the case of error).

{
  accept: function (file, done) {
    if (file.size > (1024 * 1024)) {
      done('File must be smaller than 1MB')
      return
    }

    done()
  }
}

Dragging

The most common requirement is to know when a user starts and stops dragging a file so that you can add some visual feedback to the UI. The easiest way is to make use of Scoped slots.

<template>
  <vue-clip :options="options">

    <template slot="clip-uploader-action" scope="params">
      <div v-bind:class="{'is-dragging': params.dragging}" class="upload-action">
        <h2> Click or Drag and Drop files here upload </h2>
      </div>
    </template>

  </vue-clip>
</template>

<style>
  .upload-action.is-dragging {
    background: green;
  }
</style>

Events

You can make use of vue-clip without writing any javascript code, but if you want low-level control over the upload behavior, consider listening to special events.

onInit(uploader)

Called every time the vue-clip is initiated and binds to DOM.

<template>
  <vue-clip :on-init="init">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      init (uploader) {
        // javascript uploader instance
      }
    }

  }
</script>

onAddedFile(file)

This event is invoked every time a new file gets uploaded. You can listen for this event, you want to have access to each file object within your own parent component.

<template>
  <vue-clip :on-added-file="addedFile">
  </vue-clip>
</template>

<script>
  export default {

    data: function () {
      return {
        files: []
      }
    }

    methods: {
      addedFile (file) {
        this.files.push(file)
      }
    }

  }
</script>

onRemovedFile(file)

This event is invoked every time the file has been removed. This is the nice place to make a request to your server for deleting the file.

<template>
  <vue-clip :on-removed-file="removedFile">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      removedFile (file) {
        this
        .$http
        .post(`delete/${file.customAttributes.id}`)
        .then(console.log)
        .catch(console.error)
      }
    }

  }
</script>

onSending(file, XHR, formData)

This event is emitted before making the upload HTTP request. So this is the time to modify the HTTP request and send some custom attributes.

<template>
  <vue-clip :on-sending="sending">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      sending (file, xhr, formData) {
        formData.append('_csrf', '<token>')
      }
    }

  }
</script>

onComplete(file, status, xhr)

This event is called when a file has been processed. It includes error, success both. 3rd argument will be the xhr response, if the error is returned from the server when uploading the file.

<template>
  <vue-clip :on-complete="complete">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      complete (file, status, xhr) {
        // Adding server id to be used for deleting
        // the file.
        file.addAttribute('id', xhr.response.id)
      }
    }

  }
</script>

onDragEnter

This event is invoked as soon as the user starts dragging the file.

<template>
  <vue-clip :on-drag-enter="dragging">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      dragging () {
        // user started dragging the file.
      }
    }

  }
</script>

onDragLeave

This event is invoked when the user stops dragging the file.

<template>
  <vue-clip :on-drag-leave="stoppedDragging">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      stoppedDragging () {
        // user stopped dragging the file.
      }
    }

  }
</script>

onDrop

This event is invoked when the user drops a file on the vue-clip area.

<template>
  <vue-clip :on-drop="drop">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      drop () {
        // user stopped dragging the file.
      }
    }

  }
</script>

onTotalProgress(progress, totalBytes, bytesSent)

This event returns the total upload progress for all the files. Think of it as the global progress indicator for multiple files uploaded together.

<template>
  <vue-clip :on-total-progress="totalProgress">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      totalProgress (progress, totalBytes, bytesSent) {
      }
    }

  }
</script>

onQueueComplete

The event is called when all files in the queue have been uploaded to the server.

<template>
  <vue-clip :on-queue-complete="queueCompleted">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      queueCompleted () {
      }
    }

  }
</script>

onMaxFiles

The event is called when maxFiles upload limit has been reached. This event will be fired n timesfor each file exceeding the limit. For example

  • maxFiles - 3
  • filesUploaded - 5
  • eventCalled - 2 times with file instance
<template>
  <vue-clip :on-max-files="maxFilesReached">
  </vue-clip>
</template>

<script>
  export default {

    methods: {
      maxFilesReached (file) {
      }
    }

  }
</script>

File Attributes

The file instance sent along events has following attributes.

Attribute Type Description
name String The client name of the file
status String String The file status, which can be success, error, queued, added.
width Number The file width. Only for images.
height Number The file height. Only for images.
bytesSent Number The total bytes sent to the server so far.
progress Number Total upload progress.
total Number The total number of bytes to be sent to the server.
type String The file mime-type.
size Number The file size on user disk.
dataUrl String File base64 data URL to be used for displaying images preview.
xhrResponse Object Server xhrResponse. Only contains response, responseText and statusCode
errorMessage String Error message when processing a file. If the error is returned from the server, it will be the value of XHR error. Also can be client errors for maxSize etc.
customAttributes Object Each file needs some custom attributes, for example server id to be used for deleting the files.

Adding/Accessing Custom Attributes

file.addAttribute('id', xhr.response.id)

// access id
file.customAttributes.id

Browser Support

  • Chrome 7+
  • Firefox 4+
  • IE 10+
  • Opera 12+
  • Safari 6+

Things to consider

Make sure you add class dz-message to the uploader action wrapped inside clip-uploader-action slot. This makes your entire action body clickable. There are ways to get around it, but I wanted to keep the API transparent, instead of adding a bunch of DOM elements behind the scenes.

<template slot="clip-uploader-action">
  <div>
    <div class="dz-message"><h2> Click or Drag and Drop files here upload </h2></div>
  </div>
</template>

More Repositories

1

Google-Play-Store-API

Play Store API is an unofficial version of Google Play Store which will let you pullup applications from google play store using18 different functions covering almost everything from google store
PHP
151
star
2

knex-dynamic-connection

Adds support for dynamically returning connection config for knex queries. Helpful when you want to deal with write/read replicas
TypeScript
36
star
3

alpine-teleport

A Vue style teleport for Alpine.js
JavaScript
20
star
4

gh-copy-labels

Copy labels across multiple repos at once
TypeScript
19
star
5

meta

Documenting my workflows publicly and having discussions around them.
18
star
6

angular-validation-schema

schema based validation provider for https://github.com/huei90/angular-validation
15
star
7

html-to-markdown

html to markdown converter with zero dependencies for browser and nodejs
JavaScript
14
star
8

Php-event-calendar

Php event calendar is an open source script to create and manage multiple events on a visual calendar. You can read more about it on http://www.thetutlage.com
JavaScript
10
star
9

boilerplate

A boilerplate for personal projects
TypeScript
10
star
10

Jquery-Quiz-Engine

Jquery quiz engine will let you create and manage multiple quiz from an admin panel, the user quiz interface works with help of jQuery to tweak little animations
PHP
9
star
11

Google-Analytics-Api-Php-Class

Google Analytics Php Api Class let's you access your analytics data in text and graphical way. It can be really useful in building clients dashboard and much more.
PHP
9
star
12

CRUD-Management-System---Tutorial---

CRUD stands for Create, Read , Updated and Delete Database items using a GUI based application.Source files are a part of 7 videos long tutorials series which are available on http://www.thetutlage.com
JavaScript
8
star
13

jwplayer-5

jwPlayer5 source files
8
star
14

chul

Static documentation generator used by AdonisJs and friends
JavaScript
8
star
15

hello-world-v5

A sample app
TypeScript
7
star
16

mirage.js

Mirage is Ajax mocking library for modern era development.
JavaScript
7
star
17

Pro-Newsletter-Download

Pro Newsletter is a free Php based newsletter script that will allow you to manage and send newsletters to your subscribers.
6
star
18

what-the-lunch

Make it easier for co-workers to have lunch and form friendships
CSS
6
star
19

ghost-sitemap

Generate sitemaps for your ghost blog
JavaScript
6
star
20

tdd-blog

An in-complete blog API created using TDD in AdonisJS
TypeScript
6
star
21

do-app

A dummy AdonisJS v5 application deployed on Digital ocean apps platform
TypeScript
5
star
22

japa-cli

The cli tool for Japa test runner
JavaScript
5
star
23

require-stack

Returns syntax error while requiring modules under try/catch, which is missing by default
JavaScript
5
star
24

ace-sample-project

A sample project to demonstrate usage of AdonisJS ace to create a standalone CLI app
TypeScript
5
star
25

lineup

Must have tool for your next cli app , consists of logger, progress bar, higlighter, stickers and pretty list
JavaScript
5
star
26

packages-i-use

A sane list of npm packages I usually use
4
star
27

karma-japa

Karma test framework for Japa
JavaScript
4
star
28

Thetutlage-playground

Thetutlage playground is an open source in browser code editor quite similar to js fiddle and js bin. It supports Html,Css,Javascript and other Js libraries with optional comments option.
JavaScript
4
star
29

demo-expense-management-app

A very simple CRUD app built during "Build with Hussain" live stream
TypeScript
4
star
30

static

Host for static resources
JavaScript
3
star
31

jQuery-ajax-star-rating-system

jQuery ajax start rating system is an hour long video tutorial where you will learn how to use Php,ajax,mysql and jQuery to create a complete rating system.
3
star
32

vue-mail-adonisjs

A simple example of using Vue mail with AdonisJS
TypeScript
3
star
33

adonis-auth-tutorial

JavaScript
3
star
34

Google-Maps-Using-jQuery-Json-and-Php

This repo is a part of a tutorial on thetutlage showing how to create a dynamic map using Google Maps API V2 , jQuery , JSON and Php.
PHP
3
star
35

adonis-self-belongstomany

A repo shows how to create self belongsToMany relationship
JavaScript
2
star
36

adonis-app

App layout for adonis framework
JavaScript
2
star
37

adonis4-benchmarks

This repo contains the benchmarks for AdonisJs 3.2 and 4.0
JavaScript
2
star
38

postmark-driver-app

An app to try the postmark driver from outside it
TypeScript
2
star
39

unfurling-core

Unfurl URL's in style
2
star
40

CloudBackUp

CloudBackUp is an online application to manually take filesystem and Database backup. Currently is supports any file system , sqlite and mysql based database
PHP
2
star
41

indicative

Indicative is a beautiful Laravel inspired validation library for Nodejs, with powerful promises.
JavaScript
2
star
42

Cms-Blogging-System-Using-Php

Source files are a part of a complete video tutorial series on how to create a CMS for a blog using procedural coding. Also you will learn how to implement template system using predefined methods and functions.
ActionScript
2
star
43

pg-create-extension-cleavr

Migration that attempts to create the uuid extension in postgreSQL on Cleavr
TypeScript
2
star
44

adonis-await-outside

Repl server with async/await support
JavaScript
2
star
45

i18n-ally-example-app

An example project using the i18n-ally VSCode to work with translations inside edge templates.
TypeScript
1
star
46

jQuery-WebCam-SnapShots

jQuery webcam snapshots is a complete tutorial where you will learn on how to take snapshots using webcam and then save them on to the server using Php
JavaScript
1
star
47

dotfiles

My dot files
Shell
1
star
48

japa-processors

Core processors for Japa
1
star
49

release-it-demo

Checking some workflows with release-it
1
star
50

adonis-v5-for-glitch

Starter project to be used with glitch.com
TypeScript
1
star
51

lucid-246-example

The working example showcasing usage of manyThrough for lucid-246
JavaScript
1
star
52

sub-schema-validation

Discussing https://github.com/adonisjs/core/discussions/3382
TypeScript
1
star
53

emitter-test

Reproducing https://github.com/adonisjs/core/discussions/3732
TypeScript
1
star
54

pkg-template

A template for creating package. For my personal use
JavaScript
1
star
55

dimer-nuxt-test

A test nuxt app using Dimer api
Vue
1
star
56

ecs-dummy

Hello
TypeScript
1
star
57

node-als-debugging

A dummy app trying to reproduce ALS failing when in debugging mode under certain conditions
JavaScript
1
star
58

Typescript-4-5-regression

Maybe?
TypeScript
1
star
59

adonis-websocket-auth

Sample repo reproducing the bug reported on https://forum.adonisjs.com/t/authentication-by-session-token-in-sockets/934/10
JavaScript
1
star
60

antl-switch-lang

This app shows a demo on how to build a website, which allows switching language from the website header.
JavaScript
1
star
61

Source-Files

All tutorial source files of thetutlage.com
1
star
62

Youtube-Elements-Jquery-Playlist-Plugin

Youtube Elemenets is a jquery plugin which will build a dynamic playist using just the youtube playlist id, you can choose different options to change player size and size.
JavaScript
1
star
63

Windows8-Css-Theme

Andy on thetutlage made an experiment by creating Windows8 look alike theme using Css3 and jQuery
1
star
64

lucid-alone

A repo showing how to make use of AdonisJs ORM Lucid without the entire framework.
JavaScript
1
star
65

adonis-extend-logger

Reproducing https://forum.adonisjs.com/t/cant-extend-logger/1004
JavaScript
1
star
66

require-ts-issue-2

Attempt to reproduce issue #2
TypeScript
1
star
67

hmr-demo

AdonisJS HMR demo
TypeScript
1
star
68

adonis-brew

Brew is a testing provider for AdonisJs. It makes writing Unit, Integration and Application tests a lot easier than you can imagine.
1
star