How To

Hide default drop area

You can achieve this behavior by override the corresponding uploader styles. In the following example, override the below styles to hide the default drop area behavior.

* .e-upload.e-control
* .e-upload .e-file-select
* .e-upload .e-file-drop
Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :asyncSettings= "path" ></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
    data: function() {
        return {
            path:  {
                saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
                removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
            }
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    .e-control .e-file-select,
    .e-control .e-file-drop {
        display: none;
    }

</style>

Preview images before uploading

The uploader component allows to create preview images before uploaded it. The preview images created by reading the file using selected event. Also, the user can create preview images after uploading to server using success event.

In the following link, explains about how to create image preview in uploader component.

Image Preview

Make an invisible upload

You can achieve the invisible upload feature by using selected event in uploader component. In the following example, explains how to achieve invisible upload in uploader component.

Source
Preview
app.vue
<template>
  <div>
  <div id='preview'></div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :selected = "onupload" :autoUpload= "autoUpload" :asyncSettings= "path" :allowedExtensions = "extensions" ></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { createElement, detach, EventHandler } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
          extensions: '.png, .jpg, .jpeg',
          autoUpload: false
        }
    },
    methods: {
        onupload:function(args: SelectedEventArgs){
    for(let i = 0; i< args.filesData.length ; i++){
        let liparentDiv = createElement('div',  { className: 'image-list'});
        let liImage = createElement('img',  { className: 'image'});
        liparentDiv.appendChild(liImage);
        this.readURL(liImage, args.filesData[i]);
        document.getElementById('preview').appendChild(liparentDiv);
    }
    args.cancel=true;
},

 readURL: function(liImage: HTMLElement, file: any) {
    let imgPreview: HTMLImageElement = liImage as HTMLImageElement;
    let imageFile: File = file.rawFile;
    let reader: FileReader = new FileReader();
    reader.addEventListener( 'load', () => {
        imgPreview.src = reader.result;
    }, false);
    if (imageFile) {
        reader.readAsDataURL(imageFile);
    }
};
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    #preview {
  border: 2px dashed #ddd;
  padding: 15px;
}

.image-list {
  width: 134px;
  height: 117px;
  margin-right: 4px;
  border: 1px solid lightgrey;
  display: inline-block;
}

.image {
  width: 134px;
  height: 117px;
  margin-right: 4px;
  display: inline-block;
}

.e-control {
  border : 0;
}

.e-control ul {
  border: 1px solid #ddd;
}

.e-control .e-file-select,
.e-control .e-file-drop {
  display: none;
}

</style>

Customize progressbar

You can customize the progress bar by override the styles in uploader component. In the following example, showcase about how to customize the progress bar’s size, color and progress background.

Source
Preview
app.vue
<template>
  <div id='upload_container'>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          }
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    #upload_container .e-control .e-upload-files .e-file-container .e-progress-inner-wrap .e-upload-progress {
    background: yellow;
    height: 4px;
    }

    #upload_container .e-control .e-upload-files .e-file-container .e-progress-inner-wrap {
    height: 4px;
    background-color: lightblue;
    }

</style>

Sort the selected files

You can sort the selected files list and shown the list items in meaningful order. By using selected event, you can achieve this behavior in uploader component.

In the following example, explains about how to sort the file list in uploader component.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :selected = "onSelect" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);
let initial: boolean = true;
export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          }
        }
    },
    methods: {
 onSelect: function(args: SelectedEventArgs): void {
    if (initial) { initial = false; return; }
    args.isModified = true;
    let oldFiles: FileInfo[] = this.$refs.uploadObj.getFilesData();
    let filesData: FileInfo[] = args.filesData.concat(oldFiles);
    let modifiedData: FileInfo[] = this.sortFileList(filesData);
    args.modifiedFilesData = modifiedData;
},

 sortFileList: function(filesData: FileInfo[]): FileInfo[] {
    let files: FileInfo[] = filesData;
    let fileNames: string[] = [];
    for (let i: number = 0; i < files.length; i++) {
        fileNames.push(files[i].name);
    }
    let sortedFileNames: string[] = fileNames.sort();
    let sortedFilesData: FileInfo[] = [];
    let index: number = 0;
    for (let name of sortedFileNames) {
        for (let i: number = 0; i < files.length; i++) {
            if (name === files[i].name) {
                sortedFilesData.push(files[i]);
            }
        }
    }
    return sortedFilesData;
}

    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
</style>

Get the total size of selected files

You can get the total size of selected files before upload it to designated server. By using selected event you can achieve this behavior.

In the following example, explains about how to calculate total file size before upload.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :selected = "onSelect" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          }
        }
    },
    methods: {
  onSelect:function(args: SelectedEventArgs): void {
    let totalSize: number = 0;
    for (let file of args.filesData) {
        totalSize = totalSize + file.size;
    }
    let size: string = this.$refs.uploadObj.bytesToSize(totalSize);
    alert("Total select file's size is " + size);
}
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }

</style>

Customize button with HTML element

The uploader component allows you to customize the action buttons by using buttons  property.

In the following example explains about how to customize the action buttons.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :buttons="buttons" :autoUpload="autoUpload" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { createElement } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);
let uploadEle = createElement('span', { className: 'upload e-icons' });
uploadEle.innerHTML = 'Upload All';
let clearEle = createElement('span', { className: 'remove e-icons' });
clearEle.innerHTML = 'Clear All';

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
        autoUpload: false,
        buttons: {
        browse: 'Choose file',
        clear: clearEle,
        upload: uploadEle
        }
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }

.e-upload .e-upload-actions .e-file-clear-btn,
.e-upload .e-upload-actions .e-file-upload-btn {
  -webkit-tap-highlight-color: transparent;
    background-color: #ddd;
    border-color: #c3c3c3;
    color: #000000;
    box-shadow: none;
    width: 50%;
    margin: 0;
    text-transform: none;
    padding: 8px 0;
}
.upload::before {
  content: '\e725';
  position: relative;
  font-size: 10px;
  right: 10px;
}
.remove::before {
  content: '\e932';
  position: relative;
  font-size: 10px;
  right: 10px;
}
.e-upload .e-upload-actions {
  width: 100%;
}

</style>

Add a confirmation dialog before remove files

You can customize the uploader component for use confirm dialog before remove the files. In the following example, used ej2 dialog as confirm dialog which is used for making confirmation on removing the files.

Source
Preview
app.vue
<template>

  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' :removing="onremove" name="UploadFiles"  :asyncSettings= "path"></ejs-uploader>
    <div id="dlgContainer">
     <ejs-dialog ref="dialogObj" :buttons="dlgButtons" :target="dlgContainer" :visible="false" :width='width' :content='dialogContent'>
     </ejs-dialog>
    </div>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { createElement } from '@syncfusion/ej2-base';
import { DialogPlugin } from '@syncfusion/ej2-vue-popups';
Vue.use(DialogPlugin);
Vue.use(UploaderPlugin);

let removeFile: FileInfo[];

export default {
  data: function(){
        return {
          dlgContainer: "#dlgContainer",
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            allowedExtensions: 'image/*',
            dialogContent: 'Confirm to remove the file?',
            width: '250px',
            dlgButtons: [{ click: this.dlgButtonClick, buttonModel: { content: 'OK', isPrimary: true } },
            { click: this.cancelClick, buttonModel: { content: 'Cancel' }}]
        }
    },
    methods: {
        onremove:function(args: SelectedEventArgs): void {
            this.removeFile=[];
            args.cancel = true;
            this.removeFile.push(args.filesData);
            this.$refs.dialogObj.show();
        },
        dlgButtonClick: function() {
            this.$refs.dialogObj.hide();
            this.$refs.uploadObj.remove(this.removeFile[0], false, true);
            this.removeFile = [];
        },
        cancelClick: function(){
            this.$refs.dialogObj.hide()
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    #dlgContainer {
        min-height: 350px;
        width: 100%;
    }

</style>

Validate image/* on drop

The uploader component allows you to upload all type of images by setting *image/ ** to allowedExtensions property or directly you can set it to accept attribute of uploader element.

By default, the behavior is working with select a file using browse button. But, this behavior doesn’t support on drag and drop the files. You can handle this behavior manually using selected event by filtering the file types from application.

In the following example, validated image files using images/*. You are able to drag and drop the image files with extension of PNG, JPG, BPG, GIF and TIFF to upload it.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' :selected="onSelect" name="UploadFiles" :autoUpload="autoUpload" :asyncSettings= "path" :allowedExtensions="extensions"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { DialogPlugin } from '@syncfusion/ej2-vue-popups';
import { createElement, detach } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);
Vue.use(DialogPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            autoUpload: false,
            extensions: 'image/*'
        }
    },
    methods: {
          onSelect:function(args: SelectedEventArgs): void {
                if (args.event.type === 'drop') {
            let allImages: Array<string> = ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bpg'];
            let files = args.filesData;
            let modifiedFiles = [];
            for (let file of files) {
            if (allImages.indexOf(file.type) === -1) {
                file.status = 'File type is not allowed';
                file.statusCode = '0';
            }
            modifiedFiles.push(file);
            }
            args.isModified = true;
        }
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }

</style>

Determine whether uploader has file input (required validation)

By setting required attribute to uploader input element, you can validate the file input has any value in it. In the below sample, set required attribute to the uploader input element and showcase the validation failure message using data-required-message attribute.

Source
Preview
app.vue
<template>
        <div class="col-lg-12 control-section">
            <h4 class="form-title">Photo Contest</h4>
        <div class="control_wrapper" id ="control_wrapper">
            <form id="form1" method="post">
                <div class="form-group" style="padding-top: 40px; float: left">
                    <div class="e-float-input">
                        <input type="text" id="name" name="name" data-required-message="* Enter your name" required="" data-msg-containerid="nameError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text e-label-top" for="name">Name</label>
                    </div>
                    <div id="nameError"></div>
                </div>
                <div id="dropArea">
                    <div id="uploadError" style='float: right;'></div>
                    <div id='customBrowse' class="form-group dropUpload">   Drop image here...
                    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles" :selected="onFileSelect" :autoUpload="autoUpload"></ejs-uploader>
                    </div>
                    </div>
                <div class="submitBtn">
                    <button type="button" class="submit-btn e-btn" id="submit-btn">Submit</button>
                    <div class="desc"><span>*This button is not a submit type and the form submit handled from externally.</span></div>
                    <ejs-dialog id='uploadAlert' :header='header' showCloseIcon=true :width= 'width' :content= 'dlgContent' :target= 'dlgTarget'
                :isModal= 'Modal' :visible="false" :animationSettings= 'animation' ref="dialogObj" >
                </ejs-dialog>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
import { FormValidator  } from '@syncfusion/ej2-inputs';
import { DialogPlugin } from '@syncfusion/ej2-vue-popups';
import { createElement, detach } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);
Vue.use(DialogPlugin);

export default {
  data: function(){
        return {
          dropElement: '.control-fluid',
          extensions: '.jpg, .png',
          isAuto: false,
          formObj: '',
          header: 'Success',
          animation: {effect: 'zoom'},
          Modal: true,
          dlgTarget: '.control_wrapper',
          dlgContent: 'Your details have been updated successfully, Thank you.',
          width: '335px',
            autoUpload: false
        }
    },
    mounted: function() {
          let rules;
           let options = {
        //Initialize the CustomPlacement.
            customPlacement: function(inputElement, errorElement) {
                inputElement = inputElement.closest('.form-group').querySelector('.error');
                inputElement.parentElement.appendChild(errorElement);
            },
             rules = {
                    'Name': {
                        required: true
                    },
                    'upload': {
                        required: true
                    }
                }
            }
    this.formObj = new FormValidator('#form1', options);
let localObj = this;
document.getElementById('submit-btn').onclick =             function() {
            localObj.onFormSubmit();
        };
        document.getElementById('customBrowse').onclick = () => {
    document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
};
  this.$refs.uploadObj.$el.setAttribute('data-required-message', '* Choose your image to upload');
   this.$refs.uploadObj.$el.setAttribute('required', '');
  this.$refs.uploadObj.$el.setAttribute('data-msg-containerid', 'uploadError');
    },
    methods:{
    customBrowse: function() {
        document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
    },
    onFileSelect: function(args: any): void {
    if (args.filesData.length > 0) {
        if (document.getElementsByClassName('upload-image').length > 0) {
            detach(document.getElementsByClassName('imgWrapper')[0]);
        }
        let imageTag = createElement('IMG', { className: 'upload-image', attrs: { 'alt': 'Image' } });
let wrapper = createElement('span', { className: 'imgWrapper' });
        wrapper.appendChild(imageTag);
            let rootFile = document.getElementsByClassName('dropUpload')[0];
rootFile.insertBefore(wrapper, rootFile.firstChild);
        this.readURL(wrapper, args.filesData[0]);
    }
    args.cancel = true;
},
readURL: function(li, args) {
    let preview = li.querySelector('.upload-image');
    let file: File = args.rawFile;
    let reader: FileReader = new FileReader();
    reader.addEventListener('load', () => { preview.src = reader.result; }, false);
    if (file) { reader.readAsDataURL(file); }
},

onFormSubmit: function(){
let formStatus = this.formObj.validate();
if (formStatus) {
        this.formObj.element.reset();
        detach(document.getElementsByClassName('imgWrapper')[0]);
        this.$refs.dialogObj.show();
    }
}
}
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    .address-field {
  resize: none;
}
input#fileupload {
    opacity: 0;
}
#dropArea .dropUpload .upload-image {
  height: 140px;
  width: 140px;
}
#dropArea .dropUpload {
  float: right;
  text-align: center;
  vertical-align: middle;
  line-height: 12;
  overflow: hidden;
  border: 1px dashed;
  width: 150px;
  height: 150px;
}
.e-upload {
  visibility: hidden;
}
#control_wrapper {
  max-width: 500px;
  margin: auto;
  border: 0.5px solid #BEBEBE;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.36);
  padding: 1% 4% 7%;
  background: #f9f9f9;
}
.e-error {
  padding-top:3px;
}
.control_wrapper .e-upload .e-upload-drag-hover {
  margin: 0;
}

.submit-btn {
  margin-top: 145px;
}
.submitBtn .desc {
  margin: 2% 23% 0 18%;
}
.submitBtn {
  text-align: center;
}
.form-support {
  width: 100%;
}
.success .form-support {
  display: none;
}
.success .successmsg {
  border: 0.5px solid green;
  padding: 10%;
  color: green;
}
#form1 {
  position: relative;
  top: 14%;
}
.form-support td {
  width: 100%;
  padding-top:4%;
}
.e-upload {
  float: none;
}
.choose-file{
  width: 60%;
}
#browse {
  float: right;
  margin-right: -113px;
  margin-top: -27px;
}
.form-title {
  text-align: center;
}

</style>

Achieve file upload programmatically

You can upload a file programmatically using upload method. The selected files data, get from getFilesData public method in uploader.

The upload method behaves differently based on its arguments.

  • If this method receives any files as arguments, those files only start to upload.
  • If it has no argument then all the selected files are will start to upload.
Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles"  :autoUpload="autoUpload" :asyncSettings= "path"></ejs-uploader>
    <div id="btnContainer">
        <span style='padding-left: 40px;'>
        <button id='first' style='margin-top: 30px' class='e-btn e-control'>Upload first file</button>
    </span>
    <span style=' padding-left: 40px;'>
        <button style='margin-top: 30px' id='full' class='e-btn e-control'>Upload all files</button>
    </span>
  </div>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            autoUpload: false
        }
    },
    mounted: function() {
       document.getElementById('first').onclick = (args) => {
    this.$refs.uploadObj.upload(this.$refs.uploadObj.getFilesData()[0]);
};

document.getElementById('full').onclick = (args) => {
    this.$refs.uploadObj.upload(this.$refs.uploadObj.getFilesData());
};
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    .e-upload-actions {
        display: none;
    }
    .e-btn {
        text-transform: none;
    }

</style>

Check file size before uploading it

By using uploading event, you can get the file size before upload it to server. File object contains the file size in bytes only. You can convert the size to standard formats (KB or MB) using bytesToSize method.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles"  :autoUpload="autoUpload" :asyncSettings= "path" :uploading="onBeforeUpload"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            autoUpload: false
        }
    },
    methods: {
onBeforeUpload: function(args): void {
    // get the file size in bytes
    let sizeInBytes: number = args.fileData.size;
    // get the file size in standard format
    alert("File size is: " + this.$refs.uploadObj.bytesToSize(sizeInBytes))
}
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
</style>

Check the MIME type of file before upload it

By using uploading event, you can get the file MIME type before uploading it to server. In the below sample, file MIME type is shown in the alert box before file start to upload.

Source
Preview
app.vue
<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles"  :autoUpload="autoUpload" :asyncSettings= "path" :uploading="onBeforeUpload"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            autoUpload: false
        }
    },
    methods: {
onBeforeUpload: function(args): void {
 // get the file MIME type
    alert("File MIME type is: " + args.fileData.rawFile.type)
}
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
</style>

Trigger click event of input file from external button

You can trigger the click event of input file from external button using click event of button. In the below sample, triggered click event of input file from Essential JavaScript 2 Button.

Source
Preview
app.vue
<template>
  <div id="uploaderContainer">
    <!-- Initialize Uploader -->
<div id="dropArea">
    <span id="drop"> Drop image (JPG, PNG) files here or <button class='e-btn e-control' id="browse">Browse</button></span>
</div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' name="UploadFiles"  :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          }
        }
    },
    mounted:function {
    document.getElementById('browse').onclick = () => {
        document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
    };
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }
    #dropArea {
        border: 1px dashed #c3c3cc;
        text-align: center;
        padding: 20px 0 10px;
    }
    .e-file-select-wrap {
        display: none;
    }
</style>

How to add additional data on upload

The uploader component allows you to add the additional data on file upload which is used to get in the server end. By using uploading event and its customFormData argument, you can achieve this behavior.

In the following code snippet, explains about how to add additional data on file upload.

<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' :uploading="onFileUpload" name="UploadFiles"  :autoUpload="autoUpload" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { createElement } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
            autoUpload: false,
            allowedExtensions: 'image/*'
        }
    },
    methods: {
        onFileUpload:function(args: any) {
            // add addition data as key-value pair.
            args.customFormData = [{'name': 'Syncfusion INC'}];
        }
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
    visibility: hidden;
    padding-left: 5%;
    width: 100%;
}
#loader {
    color: #008cff;
    font-family: 'Helvetica Neue','calibiri';
    font-size: 14px;
    height: 40px;
    left: 45%;
    position: absolute;
    top: 45%;
    width: 30%;
}

</style>

Server side for adding additional data

    // Get the additional data in server end by corresponding key.
    var data = HttpContext.Current.Request.Form["name"];

Open and edit the uploaded files

The uploader component allows you to modify the file after uploading to the server, which can be achieved using success event of the uploader.

You can retrieve the saved file path in the uploader success event and assign it to custom attribute (data-file-name) value of the respective file list element to open the uploaded file. Click the respective file element to create a new request along with saved file path using http header. In the server-side, get the file path from the header and open the file using process.start method

<template>
  <div>
    <ejs-uploader ref="uploadObj" id='defaultfileupload' :success="onFileUpload" name="UploadFiles" :asyncSettings= "path"></ejs-uploader>
  </div>
</template>
<script>
import Vue from 'vue';
import { UploaderPlugin, SelectedEventArgs } from '@syncfusion/ej2-vue-inputs';
import { createElement } from '@syncfusion/ej2-base';
Vue.use(UploaderPlugin);

export default {
  data: function(){
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          }
        }
    },
    methods: {
        onUploadSuccess: function(args: any) {
        let liElements: any = document.body.querySelectorAll('.e-upload-file-list');
        for (let i = 0; i < liElements.length; i++) {
            if (liElements[i].getAttribute('data-file-name') == args.file.name) {
                liElements[i].addEventListener('click', () => { this.openFile(args, event); });
                // File path have to update from server end in response status description.
                liElements[i].setAttribute('file-path', args.e.target.statusText);
            }
        }
   },
   openFile: function(args: any, e: any) {
    if (!e.target.classList.contains('e-file-delete-btn') && !e.target.classList.contains('e-file-remove-btn'))
    {
        let ajax = new XMLHttpRequest();
        // create new request for open the selected file
        ajax.open("POST", '/Home/openFile');
        let liElements = document.getElementsByClassName('e-upload')[0].querySelectorAll('.e-upload-file-list');
        for (let i = 0; i < liElements.length; i++) {
            if (liElements[i].getAttribute('data-file-name') == args.file.name) {
                // Added the file path in header to get it in server side.
            ajax.setRequestHeader('filePath', liElements[i].getAttribute('file-path').toString());
            }
        }
        ajax.send();
    }
}
    }
}
</script>
<style>
@import "../../node_modules/@syncfusion/ej2-vue-inputs/styles/material.css";
 #container {
        visibility: hidden;
        padding-left: 5%;
        width: 100%;
    }
    #loader {
        color: #008cff;
        font-family: 'Helvetica Neue','calibiri';
        font-size: 14px;
        height: 40px;
        left: 45%;
        position: absolute;
        top: 45%;
        width: 30%;
    }

</style>

Server side for open and edit the uploaded files

public void Save() {
    if (!System.IO.File.Exists(fileSavePath))
    {
        httpPostedFile.SaveAs(fileSavePath);
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        <!-- Sending the file path to client side -->
        Response.StatusDescription = fileSavePath;
        Response.End();
    }
}

[AcceptVerbs("Post")]
public void openFile()
{
    // Check whether the file is available in the corresponding location
    if (System.IO.File.Exists(Request.Headers.GetValues("filePath").First()))
    {
        // This will open the selected file from server location in desktop
        Process.Start(Request.Headers.GetValues("filePath").First());
    }
}

Resize images before uploading it to the server

You can customize the dimension of the images before uploading it to the server. By using selected event, you can get the selected file information as type of an object. From the obtained image file information, create a new canvas and render an image with the custom dimensions. Refer the corresponding code snippet as follows.

<template>
  <div>
    <div id="dropTarget">
        <span id="dropElement" class="droparea">Drop files here or <a href="" id="browse"><u>Browse</u></a> </span>
        <ejs-uploader id='template' name="UploadFiles" :asyncSettings= "path" ref="uploadObj"
            :dropArea= "dropElement" :selected= "onFileSelect" :progress= "onFileUpload"
            :success= "onUploadSuccess" :failure= "onUploadFailed" :removing= "onFileRemove">
        </ejs-uploader>
    </div>
</div>
</template>
import Vue from "vue";
import { UploaderPlugin } from '@syncfusion/ej2-vue-inputs';
import { FileInfo } from '@syncfusion/ej2-vue-inputs/uploader';
import { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';
import { createElement, isNullOrUndefined, detach, EventHandler } from '@syncfusion/ej2-base';
import { ButtonPlugin } from '@syncfusion/ej2-vue-buttons';

Vue.use(UploaderPlugin);
Vue.use(ButtonPlugin);

export default Vue.extend({
    data: function() {
        return {
          path:  {
            saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
            removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
          },
          dropElement: '#dropElement',
          filesList: [],
          filesDetails: [],
          parentElement: '',
          progressbarContainer: ''
        }
    },
    mounted: function () {
        document.getElementById('browse').onclick = function() {
        document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
        return false;
    };
    },
    methods:{
        onFileSelect: function (args) {
            args.cancel = true;
            proxy = this;
            if (isNullOrUndefined(document.getElementById('dropTarget').querySelector('.upload-list-root'))) {
                this.parentElement = createElement('div', { className: 'upload-list-root' });
                this.parentElement.appendChild(createElement('ul', {className: 'ul-element' }));
                document.getElementById('dropTarget').appendChild(this.parentElement);
            }
            for (let i = 0; i < args.filesData.length; i++) {
                this.formSelectedData(args.filesData[i]);
            }
            this.filesDetails = this.filesDetails.concat(args.filesData);
            let file = args.filesData[0].rawFile;
            let width;
            let height;
            let img = document.createElement("img");
            let reader = new FileReader();
            reader.onload = function(e) { img.src = e.target.result; };
            reader.readAsDataURL(file);
            let imgs = new Image();
            img.onload = function() {
                width = this.width;
                height = this.height;
                onNewImg(height, width, img, args.filesData[0]);
            },
            imgs.src = img.src;
        },

        // to create canvas and update our custom dimensions
        onNewImg(height, width, img, file) {
            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            let MAX_WIDTH = 1000;
            let MAX_HEIGHT = 600;
            if (width > height) {
                if (width > MAX_WIDTH) {
                    height *= MAX_WIDTH / width;
                    width = MAX_WIDTH;
                }
            } else {
                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
            }
            canvas.width = width;
            canvas.height = height;
            let ctx1 = canvas.getContext("2d");
            ctx1.drawImage(img, 0, 0, width, height);
            newImage = canvas.toDataURL("image/png");
            let blobBin = atob(newImage.split(',')[1]);
            let array = [];
            for(var i = 0; i < blobBin.length; i++) {
                array.push(blobBin.charCodeAt(i));
            }
            let newBlob = new Blob([new Uint8Array(array)], {type: 'image/png'});
            let newFile = createFile(newBlob, file);
             this.$refs.uploadObj.upload(newFile, true);
        },
        // To create File object to upload
        createFile(image, file) {
            let newFile = {
                name: file.name,
                rawFile: image,
                size: image.size,
                type: file.type,
                validationMessage: '',
                statusCode: '1',
                status: 'Ready to Upload'
            }
            return newFile;
        },
        formSelectedData: function ( selectedFiles) {
            let liEle = createElement('li',  { className: 'file-lists', attrs: {'data-file-name' : selectedFiles.name} });
            liEle.appendChild(createElement('span', {className: 'file-name ', innerHTML: selectedFiles.name }));
            liEle.appendChild(createElement('span', {className: 'file-size ', innerHTML: this.$refs.uploadObj.bytesToSize(selectedFiles.size) }));
            if (selectedFiles.statusCode === '1') {
                this.progressbarContainer = createElement('span', {className: 'progress-bar-container'});
                this.progressbarContainer.appendChild(createElement('progress', {className: 'progress', attrs: {value : '0', max : '100'}} ));
                liEle.appendChild(this.progressbarContainer);
            } else { liEle.querySelector('.file-name').classList.add('upload-fails'); }
            let closeIconContainer = createElement('span', {className: 'e-icons close-icon-container'});
            let localObj = this;
            closeIconContainer.addEventListener( 'click', function(e) {
                localObj.removeFiles(e);
            });
            liEle.appendChild(closeIconContainer); document.querySelector('.ul-element').appendChild(liEle);
            this.filesList.push(liEle);
        },

        onFileUpload: function(args) {
            let li = document.getElementById('dropTarget').querySelector('[data-file-name="' + args.file.name + '"]');
            let localObj = this;
            let progressValue = Math.round((args.e.loaded / args.e.total) * 100);
            if (!isNaN(progressValue)) {
                li.getElementsByTagName('progress')[0].value = progressValue;
            }
        },

        onUploadSuccess: function(args) {
            let spinnerElement = document.getElementById('dropTarget');
            let li= document.getElementById('dropTarget').querySelector('[data-file-name="' + args.file.name + '"]');
            if (!isNullOrUndefined(li.querySelector('.progress-bar-container'))) {
                detach(li.querySelector('.progress-bar-container'));
            }
            let localObj = this;
            if (args.operation === 'upload') {
                li.querySelector('.file-name').classList.add('upload-success');
                li.querySelector('.close-icon-container').classList.remove('remove-btn');
                li.querySelector('.close-icon-container').classList.add('delete-icon');
                (li.querySelector('.close-icon-container')).onclick = function() {
                    localObj.generateSpinner(li.querySelector('.close-icon-container'));
                };
                (li.querySelector('.close-icon-container')).onkeydown = function(e) {
                    if (e.keyCode === 13) {
                        localObj.generateSpinner(e.target.closest('.e-upload'));
                    }
                };
            }
            if (args.operation === 'remove') {
                this.filesDetails.splice(this.filesList.indexOf(li), 1);
                this.filesList.splice(this.filesList.indexOf(li), 1);
                detach(li);
                hideSpinner(li.querySelector('.close-icon-container'));
                detach(li.querySelector('.e-spinner-pane'));
            }
            alert(args.file.size);
        },

        generateSpinner: function(targetElement) {
            createSpinner({ target: targetElement, width: '25px' });
            showSpinner(targetElement);
        },

        onUploadFailed: function(args) {
            let li = document.getElementById('dropTarget').querySelector('[data-file-name="' + args.file.name + '"]');
            let localObj = this;
            li.querySelector('.file-name').classList.add('upload-fails');
            li.querySelector('.close-icon-container').classList.remove('remove-btn');
            if (args.operation === 'remove') {
                if (!isNullOrUndefined(li)) {
                    this.filesDetails.splice(this.filesList.indexOf(li), 1);
                    this.filesList.splice(this.filesList.indexOf(li), 1);
                    detach(li);
                }
            }
            if (args.operation === 'upload') {
                detach(li.querySelector('.progress-bar-container'));
            }
        },

        removeFiles: function(args) {
            if (!isNullOrUndefined(args.currentTarget)) {
                if (this.filesDetails[this.filesList.indexOf(args.currentTarget.parentElement)].statusCode === '3') { return;}
                if (this.filesDetails[this.filesList.indexOf(args.currentTarget.parentElement)].statusCode === '2' ) {
                    this.$refs.uploadObj.remove(this.filesDetails[this.filesList.indexOf(args.currentTarget.parentElement)]);
                } else  {
                    this.onFileRemove(args);
                }
            }
        },

        onFileRemove: function(args) {
            args.postRawFile = false;
            if (!isNullOrUndefined(args.currentTarget)) {
                if (this.filesDetails[this.filesList.indexOf(args.currentTarget.parentElement)].statusCode !== '2') {
                    detach(args.currentTarget.parentElement);
                    this.filesList.splice(this.filesList.indexOf(args.currentTarget.parentElement), 1);
                }
            }
        }
    }
});
<style>

    #dropTarget {
            min-height: 50px;
            padding-top: 15px;
            position: relative;
    }

    #dropElement {
        padding: 3% 30% 3%;
        display: inherit;
        border: 1px dashed #c3c3cc
    }

    .droparea {
       font-size: 13px;
    }

    .e-file-select-wrap {
        display: none;
    }

    .e-upload {
        float: none;
        border: none;
    }

    .ul-element {
        list-style: none;
        width: 100%;
        padding-left: 0;
    }

    .file-name {
        padding: 8px 6px 8px 0;
        font-size: 13px;
        width: 46%;
        display: inline-block;
        position: relative;
        top: 4px;
    }

    .file-size {
        padding: 4px;
        font-size: 13px;
        width: 18%;
        display: inline-block;
        position: relative;
    }

    .file-lists {
        border: 1px solid lightgray;
        padding: 0 6px 0 14px;
        margin-top: 15px;
        position: relative;
        background: rgba(0, 0, 0, 0.04);
    }

    .file-size, .file-name {
        font-family: "Helvetica Neue", "Helvetica", "Arial", "sans-serif";
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }

    span.progress-bar-container {
        display: block;
        float: right;
        height: 20px;
        right: 13%;
        top: 14px;
        position: relative;
        width: 20%;
    }

    .progress{
        width: 100%;
        height: 15px;
        -webkit-appearance: none;
    }

    .close-icon-container
    {
        cursor: pointer;
        font-size: 11px;
        height: 24px;
        margin: 0 12px 0 22px;
        padding: 0;
        position: absolute;
        right: 0;
        width: 24px;
        top: 6px;
    }
    .close-icon-container.remove-btn {
       display: none;
    }

    .close-icon-container.e-icons::before {
        left: 7px;
        position: inherit;
        top: 7px;
        content: '\e932';
    }

    .close-icon-container.delete-icon::before {
        content: '\e94a';
    }

    .close-icon-container:hover {
        background-color: rgba(0, 0, 0, 0.12);
        border-color: transparent;
        border-radius: 50%;
        box-shadow: 0 0 0 transparent;
    }
    .upload-success {
       color: #2bc700;
    }

    .upload-fails {
        color: #f44336;
    }

    progress::-webkit-progress-bar {
        border: 1px solid lightgrey;
        background-color: #ffffff;
        border-radius: 2px;
    }
    #dropTarget progress {
        border: 1px solid lightgrey;
        background-color: #ffffff;
        border-radius: 2px;
    }
    progress::-webkit-progress-value {
        border-radius: 2px;
        background-color: #ff4081;
    }
    #dropTarget span a {
        color:#ff4081;
    }

</style>

Convert image into binary format after uploading

By default, the file upload component saves the uploaded image files in physical directories. Also, you can convert the images into binary format at server-side before saving the uploaded images. To retrieve binary format of image files, convert the posted file’s input stream into binary reader and read as bytes using ReadBytes method.

Refer to the below server-side code snippet

[AcceptVerbs("Post")]
public void Save()
{
    try
    {
        if (System.Web.HttpContext.Current.Request.Files.AllKeys.Length > 0)
        {
            var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadFiles"];

            if (httpPostedFile != null)
            {
                byte[] fileBytes;
                using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream))
                {
                    fileBytes = br.ReadBytes((int)httpPostedFile.InputStream.Length);
                    // bytes will be stored in variable fileBytes
                }
                HttpResponse Response = System.Web.HttpContext.Current.Response;
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusCode = 200;
                Response.Status = "200 Success";
                Response.End();
            }
        }
    }
    catch (Exception e)
    {
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.StatusCode = 204;
        Response.Status = "204 No Content";
        Response.StatusDescription = e.Message;
        Response.End();
    }
}