Show custom error in SfUploader

Hello,

I have an API service that handles the file uploads. My simplified code is to send file to api (I inserted simulated error):

<SfUploader @ref="Uploader" AllowedExtensions=".pdf" AutoUpload="true" Multiple="true">
    <UploaderEvents ValueChange="OnFileUploadValueChange" ></UploaderEvents>
</SfUploader>

private async Task OnFileUploadValueChange(UploadChangeEventArgs args)
 {
     try
     {
         foreach (var file in args.Files) // Files count will be 1 here!
         {
             ApiRequest<bool> demo = new();


             using var content = new FileContentForApi();
             await content.SetFileAsync(file);
             await content.SetApiRequestAsync(demo);


             var response = await HTTP.PostAsync("http://apiip:8000/upload_file", content);
             var apiResponse = await response.GetApiResponseAsync<UploadedFilePath>();


             if (!response.IsSuccessStatusCode)
             {
                 Console.WriteLine($"Upload Failed: {apiResponse?.ToErrorMessageForLog()}");
 throw new Exception("Simulated error");
             }
         }
     }
     catch (Exception ex)
     {
 throw;
     }
}

My problem is, that in GUI the error not appear, its show succcessfull message:
Image_9360_1744279539558

I would like see this with simulated error:
Image_3059_1744279601734

Can you help me please how can I do this? Thank you!



4 Replies

YS Yohapuja Selvakumaran Syncfusion Team April 15, 2025 04:53 AM UTC

Hi SZL,

Thank you for reaching out to us.


We understand that you'd like to customize the success message displayed after a file is uploaded using the uploader component. This can be done by handling the Success event of the uploader, which is triggered when a file is successfully uploaded to the server. Within this event, you can update the StatusText property to display your own custom message.


To help you get started, we’ve prepared a sample that demonstrates how to achieve this functionality. Please refer to the code snippet below:


 

 <SfUploader @ref="UploadObj" >

                <UploaderEvents OnRemove="OnFileRemove" Success="SuccessHandler"></UploaderEvents>

                <UploaderAsyncSettings SaveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Save" RemoveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Remove"></UploaderAsyncSettings>

            </SfUploader>

 

@code{

  public void SuccessHandler(SuccessEventArgs args)

    {

        args.StatusText = "simulate error";

    }

 

}

 


In the above code:

  • The SuccessHandler method is triggered once the file upload is completed.
  • The StatusText property inside the SuccessEventArgs is modified to show a custom message instead of the default one.


For your convenience, we’ve also created a working sample that you can explore here:


Sample: https://blazorplayground.syncfusion.com/BDBeNzieCHyteawx


For more reference, you can refer to the blogs below,


https://www.syncfusion.com/forums/176802/how-to-change-status-message-of-sfuploader-programatically

https://support.syncfusion.com/kb/article/16000/handling-custom-data-with-file-upload-component-in-blazor



Regards,

Yohapuja S



SZ SZL replied to Yohapuja Selvakumaran April 15, 2025 09:42 AM UTC

Hello,

Thank you for reply.

We not used the direct api endpoint call before, because we cannot make it work with Python fastapi with unicorn.


Now I try it again, but the api call not working (I use fictiv ip in this code).


<SfUploader @ref="Uploader" AllowedExtensions=".pdf" AutoUpload="true" Multiple="true">
    <UploaderEvents BeforeUpload="@BeforeUploadHandler" Success="@SuccessHandler" OnFailure="@OnFailureHandler"></UploaderEvents>
    <UploaderAsyncSettings SaveUrl="http://6.161.88.12:8000/save2"></UploaderAsyncSettings>
</SfUploader>

In the args in BeforeUploadHandler I see the file:

Image_4718_1744709684959

But it goes into failure event every time:

Image_4185_1744709752379

Error message is always same. I see no details.


We try ~5 endpoint types in API side in python, but neither works, just like the endpoint is not accessed by the blazor call.

@app.post("/save")
async def save(upload_file: UploadFile = File(...)):
    print(f"Request received for file: {upload_file.filename}")


    if not os.path.exists(DATA_FOLDER):
        print(f"Creating directory: {DATA_FOLDER}")
        os.makedirs(DATA_FOLDER)
    else:
        print(f"Directory already exists: {DATA_FOLDER}")


    file_path = os.path.join(DATA_FOLDER, upload_file.filename)
    print(f"Target file path: {file_path}")


    if os.path.exists(file_path):
        print(f"Conflict: File already exists at {file_path}")
        raise HTTPException(status_code=409, detail="File already exists")


    print(f"Saving file to: {file_path}")
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(upload_file.file, buffer)
    print(f"File saved successfully: {upload_file.filename}")


    return {"success": True, "message": f"File uploaded successfully"}




@app.post("/save2")
async def save2(request: Request):
    print("Request received")


    # Process the multipart form data manually
    form = await request.form()


    # Find the file in the form data (Syncfusion uses names like "upload-UID")
    upload_file = None
    for key in form.keys():
        if key.startswith("upload"):
            upload_file = form[key]
            break


    if not upload_file or not isinstance(upload_file, UploadFile):
        raise HTTPException(status_code=400, detail="No file uploaded")


    print(f"Processing file: {upload_file.filename}")


    if not os.path.exists(DATA_FOLDER):
        print(f"Creating directory: {DATA_FOLDER}")
        os.makedirs(DATA_FOLDER)


    file_path = os.path.join(DATA_FOLDER, upload_file.filename)
    print(f"Target file path: {file_path}")


    if os.path.exists(file_path):
        print(f"Conflict: File already exists at {file_path}")
        raise HTTPException(status_code=409, detail="File already exists")


    print(f"Saving file to: {file_path}")
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(upload_file.file, buffer)
    print(f"File saved successfully: {upload_file.filename}")


    # Return response in format expected by Syncfusion
    return {"success": True, "message": f"File uploaded successfully"}

In browser Network window the request info is this:

Image_8292_1744709982561

When I try with syncfusion demo url, then the upload works:

https://blazor.syncfusion.com/services/production/api/FileUploader/Save

Do you have any idea, why not working with my API? This is a http API, it can be problem, that is not HTTPS?

Thank you!

BR, SZL



SZ SZL replied to SZL April 15, 2025 10:50 AM UTC

Please ignore my comment, it was HTTP <-> HTTPS problem. So we need upgrade our api to HTTPS.



SS Shereen Shajahan Syncfusion Team May 7, 2025 12:39 PM UTC

Hi SZL,

Glad to know your issue has been resolved. Please get back to us for assistance in the future.

Regards,

Shereen


Loader.
Up arrow icon