FileUpload

in namespace DotVVM.BusinessPack.Controls

Renders a FileUpload control supporting HTML 5 upload features (drag & drop, directory upload, image previews, etc.).

Usage & Scenarios

Allows the user to upload one or multiple files asynchronously.

Upload Configuration

The upload works on the background and starts immediately when the user selects the files. To make file uploading work, you have to specify where the temporary files will be uploaded.

The recommended strategy is to store the uploaded files in your application directory or in the temp directory (if your app have the appropriate permissions). To define this, you have to register the UploadedFileStorage in your Startup.cs file.

// OWIN
app.UseDotVVM<DotvvmStartup>(appPath, options: o => o.AddUploadedFileStorage("App_Data/Temp"));

// ASP.NET Core
services.AddDotVVM(o => o.AddUploadedFileStorage("App_Data/Temp"));

Using the Control

Then, you need to bind the FileUpload control to an UploadData object. It holds references to the files the user has selected and uploaded.

It has a handy property IsBusy of boolean which indicates whether the file upload is still in progress. You can use it e.g. on the button's Enabled property to disallow the user to continue until the upload is finished.

Retrieving the Stored Files

The UploadData object holds only unique IDs of uploaded files. To get the file, you have to retrieve it using the UploadedFileStorage object.

foreach (var file in UploadData.Files)
{
  if (file.Allowed)
  {
    // get the stream of the uploaded file and do whatever you need to do
    var stream = storage.GetFile(file.FileId);

    // OR you can just move the file from the temporary storage somewhere else
    var targetPath = Path.Combine(uploadPath, file.FileId + ".bin");
    storage.SaveAs(file.FileId, targetPath);
    
    // it is a good idea to delete the file from the temporary storage 
    // it is not required, the file would be deleted automatically after the timeout set in the DotvvmStartup.cs
    storage.DeleteFile(file.FileId);
  }
}

A file is not Allowed when it's type does not match the AllowedFileTypes definition or when it's size exceeds the MaxFileSize. See also the FileTypeAllowed and MaxSizeExceeded properties. You can use them to find out why the file is not allowed. But please note that these value are sent from client-side and can't be trusted in security critical scenarios.

 

Sample 1: Basic Usage

The FileUpload control has the Data property (of type UploadData). Each file will get a unique ID which is stored in this collection.

The AllowMultipleFiles property specifies whether the user can select multiple files in the file browser window. It also enables directory upload in moder browsers.

<bp:FileUpload Data="{value: Upload}" 
               AllowMultipleFiles="true" />
using System.Collections.Generic;
using DotVVM.BusinessPack.Controls;
using DotVVM.Framework.ViewModel;

namespace DotvvmWeb.Views.Docs.Controls.businesspack.FileUpload.sample1
{
    public class ViewModel : DotvvmViewModelBase
    {
        public UploadData Upload { get; set; } = new UploadData();
    }
}

Sample 2: UploadCompleted Event

The UploadCompleted event is fired automatically when file is uploaded.

<bp:FileUpload Data="{value: Upload}"
               UploadCompleted="{command: ProcessFile()}" />

{{value: Message}}
using System.Collections.Generic;
using DotVVM.BusinessPack.Controls;
using DotVVM.Framework.ViewModel;

namespace DotvvmWeb.Views.Docs.Controls.businesspack.FileUpload.sample2
{
    public class ViewModel : DotvvmViewModelBase
    {
        public string Message { get; set; }

        public UploadData Upload { get; set; } = new UploadData();

        public void ProcessFile()
        {
            // do what you have to do with the uploaded files
            Message = "ProcessFile() was called.";
        }
    }
}

Sample 3: Processing the Files

You can use the Upload.IsBusy property to determine whether the upload is still in progress or not.

<bp:FileUpload Data="{value: Upload}" />

<p>
  <bp:Button Text="Save Files" 
              Click="{command: Process()}"
              Enabled="{value: !Files.IsBusy}" />
</p>
using System.IO;
using DotVVM.BusinessPack.Controls;
using DotVVM.Framework.Storage;
using DotVVM.Framework.ViewModel;

namespace DotvvmWeb.Views.Docs.Controls.businesspack.FileUpload.sample3
{
    public class ViewModel : DotvvmViewModelBase
    {
        private readonly IUploadedFileStorage fileStorage;

        public ViewModel(IUploadedFileStorage fileStorage)
        {
            this.fileStorage = fileStorage;
        }

        public UploadData Upload { get; set; } = new UploadData();

        public void Process()
        {
            var folderPath = GetFolderdPath();

            // save all files to disk
            foreach (var file in Upload.Files)
            {
                var filePath = Path.Combine(folderPath, file.FileId + ".bin");
                fileStorage.SaveAs(file.FileId, filePath);
                fileStorage.DeleteFile(file.FileId);
            }

            // clear the data so the user can continue with other files
            Upload.Clear();
        }

        private string GetFolderdPath()
        {
            var folderPath = Path.Combine(Context.Configuration.ApplicationPhysicalPath, "MyFiles");

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            return folderPath;
        }
    }
}

Sample 4: Drag & Drop Upload

The drag & drop upload is supported out-of-the-box. And if you need to customize its look and feel, you can use the DropTemplate property. It allows you to specify contents visible when user drags files over the FileUpload control.

The DropTemplate is by default rendered over all contents of the control. If you want to open an upload dialog after an element is clicked on, mark it with bp-select-files CSS class.

<bp:FileUpload Data="{value: Upload}">
    <DropTemplate>
        Drop files here!
    </DropTemplate>
    <!-- build a custom UI here -->
    <dot:Repeater DataSource="{value: Upload.Files}">
        <div>
            {{value: FileName}}
        </div>
    </dot:Repeater>
    <bp:Button class="bp-select-files" Text="Upload" /> 
</bp:FileUpload>
using System.Collections.Generic;
using DotVVM.BusinessPack.Controls;
using DotVVM.Framework.ViewModel;


namespace DotvvmWeb.Views.Docs.Controls.businesspack.FileUpload.sample4
{
    public class ViewModel : DotvvmViewModelBase
    {
        public UploadData Upload { get; set; } = new UploadData();
    }
}

Properties

Name Type Description Notes Default Value
property icon AllowedFileTypes String Gets or sets the types of files that the server accepts. It must be a comma-separated list of unique content type specifiers (eg. ".jpg,image/png,audio/*").
attribute
inner element
static value
bindable
default
null
property icon AllowMultipleFiles Boolean Gets or sets whether the user can select multiple files at once. It is enabled by default.
attribute
inner element
static value
bindable
default
True
property icon Attributes Dictionary<String,Object>
attribute
inner element
static value
bindable
default
null
property icon ClientIDMode ClientIDMode Gets or sets the client ID generation algorithm.
attribute
inner element
static value
bindable
default
Static
property icon Data UploadData Gets or sets the file upload data (e.g. list of uploaded files, upload progress).
attribute
inner element
static value
bindable
default
null
property icon DataContext Object Gets or sets a data context for the control and its children. All value and command bindings are evaluated in context of this value.
attribute
inner element
static value
bindable
default
null
property icon DeleteIconCssClass String Gets or sets the CSS class for the icon displayed on the button used to delete uploaded files. The default value is FaRemove.
attribute
inner element
static value
bindable
default
fa fa-remove
property icon DragFilesHereText String Gets or sets the text informing about drag&drop upload; usually display next to the upload button. The default value is "or drag them here.".
attribute
inner element
static value
bindable
default
or drag them here.
property icon DropTemplate ITemplate Gets or sets the template displayed when files are dragged over the control.
attribute
inner element
static value
bindable
default
null
property icon Enabled Boolean Gets or sets a value indicating whether the control is enabled and can be modified.
attribute
inner element
static value
bindable
default
True
property icon GenericErrorText String Gets or sets the text displayed when a generic / unknown error occurs. The default value is "Upload has failed.".
attribute
inner element
static value
bindable
default
Upload has failed.
property icon ID String Gets or sets the unique control ID.
attribute
inner element
static value
bindable
default
null
property icon InnerText String Gets or sets the inner text of the HTML element.
attribute
inner element
static value
bindable
default
null
property icon MaxFileSize Int32? Gets or sets the maximum size of files in megabytes (MB). The size is not limited by default.
attribute
inner element
static value
bindable
default
null
property icon UploadButtonText String Gets or sets the text on the upload button. The default value is "Select files".
attribute
inner element
static value
bindable
default
Select files
property icon Visible Boolean Gets or sets whether the control is visible.
attribute
inner element
static value
bindable
default
True

Events

Name Type Description
event icon UploadCompleted Command Gets or sets a command that is triggered when the upload is complete.

HTML produced by the control