How to get custom errors when uploading a file to server-side.

When looking at the online samples, it shows that on exception a status-code of 204 has to be returned.
(https://blazor.syncfusion.com/documentation/file-upload/getting-started/#with-server-side-api-endpoint)

Unfortunately, the 204 still causes the Success event to fire Success instead of the OnFailured (who came up with that name, by the way?).

I tried to change the value to 400, but that just gives the standard "File failed to upload" error in the (FailureEventArgs)args.StatusText, independent of what I put in the Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase.

I also tried using to return a BadRequest("ErrorMessage"), but no avail.

Thanks for clearing this out!


9 Replies 1 reply marked as answer

JO John June 5, 2020 01:44 PM UTC

I too came across this issue just now and am looking forward to hearing about possible resolutions 


PM Ponmani Murugaiyan Syncfusion Team June 5, 2020 02:04 PM UTC

Hi Michael,  

Greetings from Syncfusion Support. 

Query 1: Unfortunately, the 204 still causes the Success event to fire Success instead of the OnFailured (who came up with that name, by the way?). 

We have validated your reported issue. We would like to inform you that from 200 to 299  is success response. So, if you provide 204, it will cause the success event to trigger success message. If you would like to show the failure message, you can provide the failure code from (400-499), it get Failure message. For more information regarding, success and failure code. Find the link below for reference. 


Query2: I tried to change the value to 400, but that just gives the standard "File failed to upload" error in the (FailureEventArgs)args.StatusText, independent of what I put in the Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase. 

From the server side, based on the status code we will update the standard text as the error message. If you want to provide custom error message, you can override the statusText as like below code snippet in respective event. 

[Index.razor] 
 
<SfUploader ID="UploadFiles1" AutoUpload="false"> 
    <UploaderEvents OnFailured="onFailure"></UploaderEvents> 
    <UploaderAsyncSettings SaveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save" RemoveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove"></UploaderAsyncSettings> 
</SfUploader> 
 
@code{ 
 
    private void onFailure(FailureEventArgs args) 
    { 
        args.StatusText = "Failed"; 
    } 
} 
 
Output: 
 
 
 

Regards,  
Ponmani M 


Marked as answer

MI Michael June 5, 2020 02:28 PM UTC

Thanks for the info.

Query 1:
I understand the response code values, but it was not clear to me as to why in the sample on the server side, an error is forwarded as 204.
After your explanation, this is still unclear.

Query 2:
What I am trying to to is to catch the error description I am getting from the server.
When the server is trowing a meaningful error, E.g. BadRequest("The excel file you have uploaded does not contain the sheet that is needed."), I would like to receive this error in the FailureEventArgs args., not set it in the client.

Thanks for looking into this.


JO John June 8, 2020 01:41 PM UTC

Really looking forward to a resolution for this also.

Have a great day!



PM Ponmani Murugaiyan Syncfusion Team June 9, 2020 02:36 AM UTC

Hi All, 

At earlier status description was available in ASP.NET. It seems recently it deprecated by Microsoft. Please find more details from the following Github link,  

We can achieve your requirement, using any of the below steps. We have provided the support for statusText to change the status description of the uploader. 

  1. We can set the status description in header in server side and can get back it in success event as mentioned below, then need to update to args.statusText.
  2. Else, we can directly update the args.statusText in client-side as per our previous update.

[Controller.cs] 

[HttpPost("[action]")] 
        public void Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles) 
        { 
            long size = 0; 
            try 
            { 
                foreach (var file in UploadFiles) 
                { 
                    var filename = ContentDispositionHeaderValue 
                            .Parse(file.ContentDisposition) 
                            .FileName 
                            .Trim('"'); 
                    var folders = filename.Split('/'); 
                    var uploaderFilePath = hostingEnv.ContentRootPath; 
                    // for Directory upload 
                    if (folders.Length > 1) 
                    { 
                        for (var i = 0; i < folders.Length - 1; i++) 
                        { 
                            var newFolder = uploaderFilePath + $@"\{folders[i]}"; 
                            Directory.CreateDirectory(newFolder); 
                            uploaderFilePath = newFolder; 
                            filename = folders[i + 1]; 
                        } 
                    } 
                    filename = uploaderFilePath + $@"\{filename}"; 
                    size += 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 = 404; 
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload"; 
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message; 
            } 
            Response.Headers.Add("status", "File failed"); 
        } 

public void OnSuccess(Syncfusion.Blazor.Inputs.SuccessEventArgs args) 
    { 
        var customHeader = new string[] { }; 
        customHeader = args.Response.Headers.Split(new Char[] { '\n' }); // To split the response header values 
        for (var i =0; i< customHeader.Length; i++) 
        { 
            if(customHeader[i].Split(new Char[] { ':' })[0]  == "status") 
            { 
                key = customHeader[i].Split(new Char[] { ':' })[0]; // To get the key pair of provided custom data in header 
                value = customHeader[i].Split(new Char[] { ':' })[1].Trim(); // To get the value for the key pair of provided custom data in header 
            } 
        } 
 
    } 

Regards, 
Ponmani M 



JO John June 25, 2020 08:23 AM UTC

Hi Ponmani and op

Apologies for the delay in getting back to you on this.
I had a go at what you suggested but couldn't get it to work, then something clicked in me and I got it to work by simply catching the error at API level

     catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 400;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
                _logger.LogCritical(e.Message, e);
            }

And at UI level

                    <SfUploader ID="UploadFiles" AllowedExtensions=".pdf"  MaxFileSize=262144000>
                            <UploaderAsyncSettings SaveUrl="@saveUrl"></UploaderAsyncSettings>
                            <UploaderEvents ValueChange="OnUploadChanged"></UploaderEvents>
                            <UploaderEvents OnFailured="OnUploadFail"></UploaderEvents>
                       </SfUploader>

private void OnUploadFail(FailureEventArgs args)
    {
        args.StatusText = args.Response.StatusText;
    }
Works like a charm!

I am not sure why I didn't do that at the start!

Hope this helps someone



PM Ponmani Murugaiyan Syncfusion Team June 26, 2020 05:38 AM UTC

Hi John, 

Thanks for the update. Please get back us if you need further assistance. 

Regards, 
Ponmani M 



AG Anthony Griggs replied to Michael December 27, 2022 02:06 PM UTC

@Michael pretty much hit the nail on the head... given your example code I see I wasn't the only one who assumed that the error would be reported to the client. Worse yet, I didn't come to this understanding until I had already published to production and had actual unreported upload failures that all gave a "Success" status! I highly suggest changing the demo to avoid confusion to others.



SP Sureshkumar P Syncfusion Team December 29, 2022 11:36 AM UTC

Hi Anthony,

Thank you for your suggestion. We appreciate your feedback and will take it into consideration as we work to improve our documentation. We will make sure to update our sample and inform you when the updated documentation is published. Thank you for taking the time to reach out to us.

Regards,

Sureshkumar P


Loader.
Up arrow icon