How to pass custom data to Blazor file uploader SaveUrl endpoint

Answer:

We can add the custom data by passing the custom parameter in the event FileSelected. We created and attached the sample based on your requirement. Kindly refer the code block

[index.razor]

<SfUploader @ref="uploadObj" ID="UploadFiles" AutoUpload="true">

<UploaderAsyncSettings SaveUrl="api/Default/Save" RemoveUrl="api/Default/Remove">UploaderAsyncSettings>

<UploaderEvents FileSelected="@Selected">UploaderEvents>

SfUploader>

@code{

SfUploader uploadObj;

FileInfo fileModel = new FileInfo();

void Selected(SelectedEventArgs args)

{

for (int i=0; i< args.FilesData.Count; i++ ) {

if(args.FilesData[i].Type == "jpg")

{

args.CurrentRequest = new List<object> { new { FileType = args.FilesData[i].Type } };

} else if(args.FilesData[i].Type == "png")

{

args.CurrentRequest = new List<object> { new { FileType = args.FilesData[i].Type } };

} else

{

args.CurrentRequest = new List<object> { new { FileType = args.FilesData[i].Type } };

}

// custom parameter in the selected event

}

}

}

[DefaultController.cs]

[HttpPost("[action]")]

public void Save(IList UploadFiles)

{

//getting filename using custom parameter

var FileName = Response.HttpContext.Request.Headers["FileType"].ToString();

long size = 0;

try

{

foreach (var file in UploadFiles)

{

var filename = ContentDispositionHeaderValue

.Parse(file.ContentDisposition)

.FileName

.Trim('"');

filename = hostingEnv.ContentRootPath + $@"\{FileName}";

size += (int)file.Length;

if (!System.IO.File.Exists(filename))

{

using (FileStream fs = System.IO.File.Create(filename))

{

file.CopyTo(fs);

fs.Flush();

}

}

}

}

catch (Exception e)

{

Response.Clear();

Response.StatusCode = 204;

Response.HttpContext.Features.Get().ReasonPhrase = "File failed to upload";

Response.HttpContext.Features.Get().ReasonPhrase = e.Message;

}

}

[HttpPost("[action]")]

public void Remove(IList UploadFiles)

{

try

{

//getting filename using custom parameter

var FileName = Response.HttpContext.Request.Headers["FileName"].ToString();

var filename = hostingEnv.ContentRootPath + $@"\{FileName}";

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

{

System.IO.File.Delete(filename);

}

}

catch (Exception e)

{

Response.Clear();

Response.StatusCode = 200;

Response.HttpContext.Features.Get().ReasonPhrase = "File removed successfully";

Response.HttpContext.Features.Get().ReasonPhrase = e.Message;

}

}

}

Find the sample for pass custom data to Blazor file uploader SaveUrl endpoint from here.


Loader.
Up arrow icon