the file uploaded in chuncks is incomplete

Hi.. 

I have a issue with the fle upload in chuncks..

the file is uploaded incomplete

the code is this


@page "/"

@using Syncfusion.Blazor.DropDowns

@using Syncfusion.Blazor.Inputs


<SfUploader ID="UploadFiles">

    <UploaderAsyncSettings SaveUrl="api/SampleData/Save" RemoveUrl="api/SampleData/Remove" ChunkSize="500000"></UploaderAsyncSettings>

    <UploaderEvents OnChunkUploadStart="@OnChunkUploadStartHandler" OnChunkSuccess="@OnChunkSuccessHandler" Success="@SuccessHandler" OnChunkFailure="@OnChunkFailureHandler"></UploaderEvents>

</SfUploader>

@code {


    private void SelectedHandler(SelectedEventArgs args)

    {

        args.CustomFormData = new List<object> { new { Name = "Syncfusion" } };

        var accessToken = "Authorization_token";

        args.CurrentRequest = new List<object> { new { Authorization = accessToken } };

    }


    private void OnChunkUploadStartHandler(UploadingEventArgs args)

    {

        args.CustomFormData = new List<object> { new { Name = "Syncfusion" } };

        var accessToken = "Authorization_token";

        args.CurrentRequest = new List<object> { new { Authorization = accessToken } };

    }


private void OnChunkSuccessHandler(SuccessEventArgs args)

{

// Here, you can customize your code.

}

private void SuccessHandler(SuccessEventArgs args)

{

// Here, you can customize your code.

}

private void OnChunkFailureHandler(FailureEventArgs args)

{

// Here, you can customize your code.

}

}


and the controller is


using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.FileProviders;


namespace BlazorUploadAndDownload.Data

{

    [Route("api/[controller]")]

    public class SampleDataController : Controller

    {

        public string uploads = ".\\Uplo"; // replace with your directory path


        [HttpPost("[action]")]

        public async Task<IActionResult> Save(IFormFile UploadFiles) // Save the uploaded file here

        {

            if (UploadFiles.Length > 0)

            {

                var filePath = Path.Combine(uploads, UploadFiles.FileName);

                if (System.IO.File.Exists(filePath))

                {

                    //Return custom-error if file already exists

                    Response.Headers.Append("custom-error", "File already exists.");


                    //Return conflict status code

                   // return new StatusCodeResult(StatusCodes.Status409Conflict);

                }

                using (var fileStream = new FileStream(filePath, FileMode.Create))

                {

                    //Save the uploaded file to server

                    await UploadFiles.CopyToAsync(fileStream);

                }

            }

            //Return success response

            Response.Headers.Append("success", "File saved successfully.");

            return Ok();

        }


        [HttpPost("[action]")]

        public void Remove(string UploadFiles) // Delete the uploaded file here

        {

            if (UploadFiles != null)

            {

                var filePath = Path.Combine(uploads, UploadFiles);

                if (System.IO.File.Exists(filePath))

                {

                    //Delete the file from server

                    System.IO.File.Delete(filePath);

                }

            }

        }


        [HttpGet("[action]")]

        public FileResult Download(string filename)

        {

            var filePath = Path.Combine(Directory.GetCurrentDirectory() + "\\Uplo");

            IFileProvider provider = new PhysicalFileProvider(filePath);

            IFileInfo fileInfo = provider.GetFileInfo(filename);

            var readStream = fileInfo.CreateReadStream();

            var mimeType = "application/pdf";

            return File(readStream, mimeType, filename);

        }


        public IActionResult Index()

        {

            return View();

        }

    }

}





Attachment: uploadfile_37eec646.zip

1 Reply

SM Suresh Masanam Syncfusion Team December 3, 2025 05:25 AM UTC

Hi Facuna,

            You’re seeing an “incomplete file” because your Save action always writes with FileMode.Create and assumes a full file arrives in a single request. With chunk upload enabled, each request contains only a slice of the file. You must detect chunk Index/total Chunk on the server and append the chunk until the last one arrives, then finalize the file.

You need to:

  • Detect chunk metadata (chunk index, total chunks, file name).
  • Append chunks to the file instead of recreating it.
  • Finalize the file when all chunks are uploaded.

Here’s an example of how to handle chunked uploads:

[HttpPost("[action]")]

public async Task<IActionResult> Save(IFormFile UploadFiles)

{

    try

    {

        if (UploadFiles.Length > 0)

        {

            var fileName = UploadFiles.FileName;

            // Create upload directory if it doesn't exist

            if (!Directory.Exists(uploads))

            {

                Directory.CreateDirectory(uploads);

            }

            if (UploadFiles.ContentType == "application/octet-stream") //Handle chunk upload

            {

                // Fetch chunk-index and total-chunk from form data

                var chunkIndex = Request.Form["chunk-index"];

                var totalChunk = Request.Form["total-chunk"];

                // Path to save the chunk files with .part extension

                var tempFilePath = Path.Combine(uploads, fileName + ".part");

                using (var fileStream = new FileStream(tempFilePath, chunkIndex == "0" ? FileMode.Create : FileMode.Append))

                {

                    await UploadFiles.CopyToAsync(fileStream);

                }


                // If all chunks are uploaded, move the file to the final destination

                if (Convert.ToInt32(chunkIndex) == Convert.ToInt32(totalChunk) - 1)

                {

                    var finalFilePath = Path.Combine(uploads, fileName);


                    // Move the .part file to the final destination without the .part extension

                    System.IO.File.Move(tempFilePath, finalFilePath);

                    return Ok(new { status = "File uploaded successfully" });

                }

                return Ok(new { status = "Chunk uploaded successfully" });

            }

            else //Handle normal upload

            {

                var filePath = Path.Combine(uploads, fileName);

                using (var fileStream = new FileStream(filePath, FileMode.Create))

                {

                    await UploadFiles.CopyToAsync(fileStream);

                }

                return Ok(new { status = "File uploaded successfully" });

            }

        }

        return BadRequest(new { status = "No file to upload" });

    }

    catch (Exception ex)

    {

        return StatusCode(500, new { status = "Error", message = ex.Message });

    }

}



This controller will correctly assemble chunked uploads and keep your non-chunked uploads working.

Documentation Link: https://blazor.syncfusion.com/documentation/file-upload/chunk-upload#cancel-upload


Regards,

Suresh


Attachment: BlazorUploaderSample_34907d3a.zip

Loader.
Up arrow icon