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:
I would like see this with simulated error:
Can you help me please how can I do this? Thank you!
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
Regards,
Yohapuja S
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:
But it goes into failure event every time:
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:
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
Please ignore my comment, it was HTTP <-> HTTPS problem. So we need upgrade our api to HTTPS.
Hi SZL,
Glad to know your issue has been resolved. Please get back to us for assistance in the future.
Regards,
Shereen
- 4 Replies
- 3 Participants
-
SZ SZL
- Apr 10, 2025 10:07 AM UTC
- May 7, 2025 12:39 PM UTC