New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

vue-multi-uploader

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vue-multi-uploader

[![Version](https://img.shields.io/npm/v/vue-multi-uploader.svg?style=flat-square)](https://www.npmjs.com/package/vue-multi-uploader) [![License](https://img.shields.io/npm/l/vue-multi-uploader.svg?style=flat-square)](LICENSE)

latest
npmnpm
Version
0.1.12
Version published
Weekly downloads
3
50%
Maintainers
1
Weekly downloads
 
Created
Source

Vue Multi Uploader

Version License

A headless upload component that supports developers to custom for every project. DEMO

Installation

npm i vue-multi-uploader --save

# OR

yarn add vue-multi-uploader

Getting Started

Use bundler and Vue SFC:


<script setup lang="ts">
  import { useMultiUploader } from 'vue-multi-uploader';
</script>

Include JS file.


<script src="path/to/package/dist/vue-multi-uploader.umd.cjs"></script>

<script>
  VueMultiUploader.useMultiUploader();
</script>

ES Module


<script type="module">
  import { useMultiUploader } from 'path/to/package/dist/vue-multi-uploader.js';

  useMultiUploader();
</script>

Usage

This is a simple example of how to use the vue-multi-uploader component in a Vue 3 application. The example demonstrates how to set up a file upload interface with drag-and-drop functionality, progress indicators, and the ability to delete uploaded items.

Full example please refer to Demo.


<script setup lang="ts">
  import {
    type UploaderItem,
    useMultiUploader,
  } from 'vue-multi-uploader';
  import { ref, useTemplateRef } from 'vue';

  const dropzone = useTemplateRef('dropzone');

  const items = ref < UploaderItem[] > ([]);

  const {
    openFileSelector,
    deleteItem
  } = useMultiUploader(items, '/api/upload', {
    dropzone: dropzone,
    maxFiles: 5,
    onItemUploadSuccess(item, xhr) {
      const res = JSON.parse(xhr.responseText);
      item.url = res.url;
    },
  });

</script>

<template>
  <div class="">
    <!-- File List -->
    <ul>
      <li v-for="(item) of items" :key="item.key">
        <!-- Item title -->
        <div>
          {{ item.title }}
        </div>

        <!-- Progress -->
        <div class="progress progress-sm" style="height: 0.5rem">
          <div class="progress-bar" :style="{ width: (item.progress * 100) + '%' }"></div>
        </div>

        <!-- Delete Button-->
        <a href="#" @click.prevent="deleteItem(item)">
          Delete
        </a>
      </li>
    </ul>

    <!-- Dropzone -->
    <div ref="dropzone" class="dropzone"
      style="height: 300px; cursor: pointer;"
      @click="openFileSelector"
    >
      <div class="dropzone__content text-center">
        <span class="fa-solid fa-upload" style="font-size: 2rem"></span>
        <div>Click or drop to upload</div>
      </div>
    </div>
  </div>
</template>

Options

Every option item can be a value, Ref, computed, or function to make them reactive.

const disabledRef = ref(props.disabled);

useMultiUploader(items, '/api/upload', {
  maxFiles: 5, // Value
  maxConcurrent: () => 2, // Getter
  disabled: disabledRef, // Ref
});

Options Refs

NameTypeDefaultDescription
idstringundefinedID for the uploader instance, leave empty will auto generate.
acceptstringundefinedAccepted file types for upload, separate by comma if multiple, can be mime type (image/*, text/plain) or ext name .jpg, .png.
maxFilesnumberundefinedMaximum number of files allowed for upload.
maxConcurrentnumber2Maximum number of concurrent uploads.
maxItemSizenumberundefinedMaximum size of a single file in bytes.
disabledbooleanfalseDisables the uploader if set to true.
readonlybooleanfalseSets the uploader to read-only mode if set to true.
dropzoneMaybeElementundefinedElement or ElementRef to be used as the dropzone.
onDragClassstringh-ondragCSS class to apply when dragging files over the dropzone.
autoStartbooleantrueAutomatically start uploading files when added, if set to false, you must call uploadStart() to start.
prepareXhr(xhr: XMLHttpRequest) => MaybePromise<XMLHttpRequest or void>undefinedA function to configure the XMLHttpRequest object or return a new XMLHttpRequest object, can be async.
onChange(items: UploaderItem[]) => voidTriggered when the uploader items change.
onDeleteItem(item: UploaderItem) => voidTriggered when an item is deleted from uploader.
onUploading() => voidTriggered when uploading process starts.
onUploaded() => voidTriggered when uploading process completes.
headersRecord<string, string>Custom headers to be sent with the upload request.
dataRecord<string, any>Custom data to be sent with the upload request.
onItemUploadStart(item: UploaderItem, xhr: XMLHttpRequest) => voidTriggered when an individual file upload starts.
onItemUploadSuccess(item: UploaderItem, xhr: XMLHttpRequest) => voidTriggered when a file uploads successfully, you can get the API return url here and set to item.
onItemUploadFail(item: UploaderItem, xhr: XMLHttpRequest) => voidTriggered when a file fails to upload.
onItemUploadEnd(item: UploaderItem, xhr: XMLHttpRequest) => voidTriggered when an individual file upload finishes.
onItemUploadProgress(item: UploaderItem, event: ProgressEvent) => voidTriggered during upload progress of a file.
onInvalidFile(e: Error) => voidTriggered when a file with an invalid type or size is selected.

Return Values

Variables can be directly obtained by expanding the return values as follows:

const {
  id,
  accept,
  maxFiles,
  maxConcurrent,
  disabled,
  readonly,
  items,
  uploading,
  progress,
  addFiles,
  removeItem,
  clear,
  startUpload,
  eventBus,
  headers,
  data,
} = useMultiUploader(...)

Modifiable Values

NameTypeDescription
acceptRef<string>Accepted file types string (e.g., .jpg,.png)
disabledRef<boolean>Whether the uploader is disabled
idRef<string>Unique identifier for the uploader instance
itemsRef<UploaderItem[]>List of file items currently in the uploader
maxConcurrentRef<number>Maximum number of concurrent uploads
maxFilesRef<number or undefined>Maximum number of files allowed
maxItemSizeRef<number or undefined>Maximum size of a single file in bytes
readonlyRef<boolean>Whether the uploader is in read-only mode
uploadUrlRef<string>Target URL for uploads
headersRecord<string, string>Custom headers to be sent with the upload request.
dataRecord<string, any>Custom data to be sent with the upload request.

Readonly Values

NameTypeDescription
acceptedTypesRef<string[]>Array of accepted file types
canUploadRef<boolean>Whether uploading is allowed, if is readonly or disabled or reaches max files, this will be false
eventBusEmitterCustom event bus for listening and triggering events
isReadonlyRef<boolean>Whether the uploader is in read-only state, this will merge disabled and readonly
isUploadingRef<boolean>Whether an upload is currently in progress
totalSizeRef<number>Total size of all files in the uploader

Methods

NameTypeDescription
addFile(file: File) => UploaderItemAdd a file to the uploader
addItem(item: UploaderItem) => UploaderItemAdd an item to the uploader
createItem(file: File) => UploaderItemCreate a new item based on the file
deleteItem(child: UploaderItem) => voidDelete a specific file item from the uploader
emits(event: string, ...args: any[]) => voidManually trigger specific events
isImage(filePath: string) => booleanDetermine if a file is an image based on its path
isImageItem(item: UploaderItem) => booleanDetermine if an item is an image based on UploaderItem
on(event: string, callback: (...event: any[]) => void) => () => voidRegister event listeners and return a function to remove the listener
openFileSelector() => voidOpen the file selection window
uploadStart() => Promise<PromiseSettledResult<UploaderItem>[]>Start the upload process and return the result for each item
stopItemUpload(item: UploaderItem or XMLHttpRequest) => voidStop the upload process for a specific item
enqueueUploadFile(item: UploaderItem) => Promise<UploaderItem>Enqueue a file for upload, returns the created item or null if not added
uploadFile(item: UploaderItem) => Promise<UploaderItem>Upload a single file, returns the uploaded item
checkFile(file: File) => voidCheck if a file is valid, throw an Error if invalid

Note you can modify some of the values in the return values, such as disabled, readonly, maxFiles etc. The change will be reflected in the uploader instance.

Prepare Default Items

If you have some exists files that you want to show in the uploader, you can prepare them in advance.

import { type UploaderItem, useMultiUploader } from 'vue-multi-uploader';

const defaultItems = ref<UploaderItem[]>([
  {
    key: '1',
    title: 'File 1',
    url: 'https://example.com/file1.jpg',

    // The original database record data can be stored in the `data` prop.
    data: {
      id: 1,
      title: 'File 1',
      // ...
    },
  },
  {
    key: '2',
    title: 'File 2',
    url: 'https://example.com/file2.jpg',

    // The original database record data can be stored in the `data` prop.
    data: {
      id: 1,
      title: 'File 1',
      // ...
    },
  },
]);

const { items, ... } = useMultiUploader(defaultItems, '/api/upload', {
  ...,
});

The UploaderItem interface is as follows:

export interface UploaderItem {
  key: string;
  url: string;
  thumbUrl?: string;
  title?: string;
  file?: File;
  data?: Record<string, any>;

  uploadState: UploadState; // enum
  progress: number;
  xhr?: XMLHttpRequest;
  error?: Error;

  [props: string]: any;
}

Fetch Uploaded Data And Set to Item

You can set the uploaded URL to the item after the upload is complete. Use the onItemUploadSuccess callback to do this.

const {
  ...
} = useMultiUploader(items, '/api/upload', {
  onItemUploadSuccess(item, xhr) {
    const res = JSON.parse(xhr.responseText);
    item.url = res.url;

    // If thumb image is smaller than the original image, you can set it to `thumbUrl`.
    item.thumbUrl = res.thumb_url;

    // If you want to store some returned data to the item, you can set it to `data` prop.
    item.data = res.data;
  },
});

Programmatically Control

Adding Items

You can add items programmatically by using the addFile or addItem method. If autoStart is set to true, the upload will start automatically after adding the item.

const {
  addFile,
  addItem,
  createItem,
} = useMultiUploader(items, '/api/upload', {
  ...
});

// Add a file
const item = addFile(file); // Return UploaderItem

// Add an item
const item = createItem(file);
addItem(item);

If autoStart is set to false, you need to call uploadStart().

const {
  addFile,
  uploadStart,
} = useMultiUploader(items, '/api/upload', {
  autoStart: false,
  ...
});

const item = addFile(file);

uploadStart();

Stop Upload

You can stop the upload process for a specific item by using the stopItemUpload method.

const {
  stopItemUpload,
} = useMultiUploader(items, '/api/upload', {
  ...
});

function clickToStop(item: UploaderItem) {
  stopItemUpload(item);

  // Or stop by xhr
  stopItemUpload(item.xhr);
}

Handle Errors

Invalid File

If the file is invalid, you can handle it in the onInvalidFile callback.

const {
  ...
} = useMultiUploader(items, '/api/upload', {
  onInvalidFile(e) {
    if (e.name === 'InvalidFileType') {
      console.error('Invalid file type:', e.message, e.file, e.accepted as string[]);
    } else if (e.name === 'InvalidFileSize') {
      console.error('Invalid file size:', e.message, e.file, e.maxSize);
    }
  },
});

Upload Fail

If the upload fails, you can handle it in the onItemUploadFail callback.

const {
  ...
} = useMultiUploader(items, '/api/upload', {
  onItemUploadFail(item, xhr) {
    console.error('Upload failed:', item.error, xhr);
  },
});

Events

You can use the on method to listen to events.

const { on } = useMultiUploader(items, '/api/upload', {});

const off = on('item-upload-success', (item, xhr) => {
  console.log('Item uploaded successfully:', item);
});

onUnmounted(() => {
  // Remember release the event listener
  off();
});

The eventBus is a dush() instance, so there are some features you can use:

const { eventBus } = useMultiUploader(items, '/api/upload', {});

eventBus.on('...', () => {...
});
eventBus.once('...', () => {...
});

The following events will match to on* callback in options:

EventCallback
changeonChange
delete-itemonDeleteItem
uploadingonUploading
uploadedonUploaded
create-itemonCreateItem
item-upload-startonItemUploadStart
item-upload-successonItemUploadSuccess
item-upload-failonItemUploadFail
item-upload-endonItemUploadEnd
item-upload-progressonItemUploadProgress
invalid-fileonInvalidFile

Pre-Built Components

There has a VueMultiUploader component that is a pre-built component for the uploader. Here is a simple example of how to use it.


<script setup lang="ts">
  import { MultiUploader, ItemCard, ItemCardPlaceholder } from 'vue-multi-uploader';
  import { ref } from 'vue';

  const items = ref([]);
  const uploadUrl = '/api/upload';
  const accept = '.jpg,.png';

  function onItemUploadSuccess(item, xhr) {
    console.log('Item uploaded successfully:', item);
  }

  function deleteItem(item) {
    // Remove the item from the list
  }
</script>
<template>
  <MultiUploader
    :items="items"
    :upload-url="uploadUrl"
    :max-files="5"
    :max-concurrent="2"
    :accept="accept"
    @item-upload-success="onItemUploadSuccess"
  >
    <template #items="{items, instance: {canUpload, openFileSelector, deleteItem}}">
      <div class="d-flex flex-wrap w-100 gap-3">
        <ItemCard v-for="(item, index) of items"
          :item
          :i="index"
          @delete="deleteItem"
        />

        <ItemCardPlaceholder
          v-if="canUpload"
          class=""
          text="Click or drop to upload"
          @click="openFileSelector"
        />
      </div>
    </template>
  </MultiUploader>
</template>

Examples please refer to Demo.

Get Uploader Instance From Component

You can get the uploader instance from the component.


<script setup lang="ts">
  import { MultiUploader } from 'vue-multi-uploader';
  import { onMounted, useTemplateRef } from 'vue';

  const uploader = useTemplateRef('uploader');

  onMounted(() => {
    const { items, uploadUrl, maxFiles } = uploader.value!.instance;
    console.log(items, uploadUrl, maxFiles);
  });
</script>
<template>
  <MultiUploader ref="uploader" ...>
    ...
  </MultiUploader>
</template>

Keywords

vue

FAQs

Package last updated on 27 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts