FileUpload

in namespace DotVVM.Framework.Controls

Renders a FileUpload control allowing users to upload one or multiple files asynchronously.

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 UploadedFilesCollection. It is a collection which will hold references to the files the user has selected and uploaded.

This collection has a handy property IsBusy of boolean which indicated 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 UploadedFilesCollection holds only unique IDs of uploaded files. To get the file, you have to retrieve it using the UploadedFileStorage object.

foreach (var file in UploadedFiles.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 FileUpload control

The FileUpload control has the UploadedFiles property (of type UploadedFilesCollection). 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.

<dot:FileUpload UploadedFiles="{value: Files}" AllowMultipleFiles="true" />
using System.Collections.Generic;
using DotVVM.Framework.Controls;

namespace DotvvmWeb.Views.Docs.Controls.builtin.FileUpload.sample1
{
    public class ViewModel
    {
        public UploadedFilesCollection Files { get; set; }


        public ViewModel()
        {
            Files = new UploadedFilesCollection();
        }
        
    }
}

Sample 2: UploadCompleted Event

The UploadCompleted event is fired automatically when file is uploaded.

<dot:FileUpload UploadedFiles="{value: Files}" AllowMultipleFiles="true" 
                UploadCompleted="{command: ProcessFile()}" />

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

namespace DotvvmWeb.Views.Docs.Controls.builtin.FileUpload.sample2
{
    public class ViewModel
    {
        public UploadedFilesCollection Files { get; set; }

        public string Message { get; set; }

        public ViewModel()
        {
            Files = new UploadedFilesCollection();
        }

        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 Files.IsBusy property to determine whether the upload is still in progress or not.

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

namespace DotvvmWeb.Views.Docs.Controls.builtin.FileUpload.sample3
{
    public class ViewModel : DotvvmViewModelBase
    {
        public UploadedFilesCollection Files { get; set; }


        public ViewModel()
        {
            Files = new UploadedFilesCollection();
        }


        public void Process()
        {
            var storage = Context.Configuration.ServiceLocator.GetService<IUploadedFileStorage>();

            var uploadPath = GetUploadPath();

            // save all files to disk
            foreach (var file in Files.Files)
            {
                var targetPath = Path.Combine(uploadPath, file.FileId + ".bin");
                storage.SaveAs(file.FileId, targetPath);
                storage.DeleteFile(file.FileId);
            }

            // clear the uploaded files collection so the user can continue with other files
            Files.Clear();
        }

        private string GetUploadPath()
        {
            var uploadPath = Path.Combine(Context.Configuration.ApplicationPhysicalPath, "MyFiles");
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            return uploadPath;
        }
    }
}

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/*"). All file types are allowed by default.
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 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 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 NumberOfFilesIndicatorText String Gets or sets the text on the indicator showing number of files. The default value is "{0} files". The number of files will be substituted for the "{0}" placeholder.
attribute
inner element
static value
bindable
default
{0} files
property icon SuccessMessageText String Gets or sets the text that appears when all files are uploaded successfully.
attribute
inner element
static value
bindable
default
The files were uploaded successfully.
property icon UploadButtonText String Gets or sets the text on the upload button. The default value is "Upload".
attribute
inner element
static value
bindable
default
Upload
property icon UploadedFiles UploadedFilesCollection Gets or sets a collection of uploaded files.
attribute
inner element
static value
bindable
default
null
property icon UploadErrorMessageText String Gets or sets the text that appears when there is an error during the upload.
attribute
inner element
static value
bindable
default
Error occured.
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