Skip to main content

DxUpload.ChunkSize Property

Specifies the chunk size in bytes.

Namespace: DevExpress.Blazor

Assembly: DevExpress.Blazor.v23.2.dll

NuGet Package: DevExpress.Blazor

Declaration

[Parameter]
public int ChunkSize { get; set; }

Property Value

Type Description
Int32

The chunk size in bytes.

Remarks

The Upload can split large files into small packets and send them to the server in multiple requests (one by one). To enable chunk upload, set the ChunkSize property to a positive value that specifies the packet size in bytes.

<DxUpload Name="myFile" UploadUrl="https://localhost:10000/api/Upload/Upload/"
          ChunkSize="1000000">
</DxUpload>

On the server, configure your controller to process file chunks. To access the uploaded file, use the Upload’s Name property value. To get information about the file chunk, use a JSON object with the same structure as the CnunkMetadata class in the example below.

To access file and chunk metadata, use the following ways:

  • Create an action with parameters. The first parameter’s name should match the Name property value. The second parameter should be a string that defines chunk metadata serialized to JSON.

    public ActionResult UploadFile(IFormFile myFile, string chunkMetadata) {
        // ...
        var metaDataObject = JsonConvert.DeserializeObject<ChunkMetadata>(chunkMetadata);
        // ...
    }
    
  • Get the uploaded file and chunk metadata from form variables.

    public ActionResult UploadFile() {
        // ...
        var myFile = Request.Form.Files["myFile"];
        var chunkMetadata = Request.Form["chunkMetadata"];
        var metaDataObject = JsonConvert.DeserializeObject<ChunkMetadata>(chunkMetadata);
        // ...
    }
    

In the upload action, merge chunks and save the resulting file to the target location.

using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

// Declare a class that stores chunk details.
public class ChunkMetadata {
    public int Index { get; set; }
    public int TotalCount { get; set; }
    public int FileSize { get; set; }
    public string FileName { get; set; }
    public string FileType { get; set; }
    public string FileGuid { get; set; }
}

[Route("api/[controller]")]
public class UploadController : ControllerBase {
    private readonly IWebHostEnvironment _hostingEnvironment;

    public UploadController(IWebHostEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost]
    // "myFile" is the value of the Upload's "Name" property.
    public ActionResult UploadChunkFile(IFormFile myFile, string chunkMetadata) {
        // Specify the location for temporary files.
        var tempPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
        // Remove temporary files.
        RemoveTempFilesAfterDelay(tempPath, new TimeSpan(0, 5, 0));

        try {
            if (!string.IsNullOrEmpty(chunkMetadata)) {
                // Get chunk details.
                var metaDataObject = JsonConvert.DeserializeObject<ChunkMetadata>(chunkMetadata);
                // Specify the full path for temporary files (inluding the file name).
                var tempFilePath = Path.Combine(tempPath, metaDataObject.FileGuid + ".tmp");
                // Check whether the target directory exists; otherwise, create it.
                if (!Directory.Exists(tempPath))
                    Directory.CreateDirectory(tempPath);
                // Append the chunk to the file.
                AppendChunkToFile(tempFilePath, myFile);
                // Save the file if all chunks are received.
                if (metaDataObject.Index == (metaDataObject.TotalCount - 1))
                    SaveUploadedFile(tempFilePath, metaDataObject.FileName);
            }
        } catch {
            return BadRequest();
        }
        return Ok();
    }
    void AppendChunkToFile(string path, IFormFile content) {
        using(var stream = new FileStream(path, FileMode.Append, FileAccess.Write)) {
            content.CopyTo(stream);
        }
    }
    void SaveUploadedFile(string tempFilePath, string fileName) {
        var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
        System.IO.File.Copy(tempFilePath, Path.Combine(path, fileName));
    }
    void RemoveTempFilesAfterDelay(string path, TimeSpan delay) {
        var dir = new DirectoryInfo(path);
        if(dir.Exists)
            foreach(var file in dir.GetFiles("*.tmp").Where(f => f.LastWriteTimeUtc.Add(delay) < DateTime.UtcNow))
                file.Delete();
    }
}

Users can pause or cancel file upload, if the AllowPause and AllowCancel properties are set to true.

Upload Chunk Upload

Run Demo: Upload - Chunk Upload

See Also