how to preview the preloaded image in sfUploader
Hi,
I tried so hard to preview and I've got the answer from a conversation we made https://www.syncfusion.com/forums/196902/preview-multiple-image-in-sfuploader but the link does not work to continue .
anyway I got the way of previewing but now when I make a component to add a record I do not know how to display the image for edit page because as you know it would be better to display the image in editing and if the admin want to change it it's his/her choice
@page "/aboutUs/edit"
@inject HttpClient Http
@inject NavigationManager Navigate
<h3> Create About Us</h3>
<EditForm Model="aboutUs" OnSubmit="Submit">
<div class="form-grid">
<div class="editor-section">
<SfRichTextEditor @bind-Value="aboutUs.Description" Height="300px"></SfRichTextEditor>
</div>
<div class="uploader-section">
<SfUploader @ref="uploadObj" AllowedExtensions=".jpg,.jpeg,.png" ShowFileList="true" AllowMultiple="false">
<UploaderFiles>
<UploaderUploadedFiles Name="@aboutUs.Image" Size="500000" Type=".jpg" />
</UploaderFiles>
<UploaderTemplates>
<Template Context="HttpContext">
<span class="wrapper">
<img class="upload-image" alt="Preview Image @(HttpContext.Name)"
src="/uploads/@aboutUs.Image" />
</span>
<div class="name file-name" title="@HttpContext.Name">@HttpContext.Name</div>
<div class="file-size">@fileSize</div>
<span class="e-icons e-file-remove-btn" id="removeIcon" title="Remove"
@onclick="() => onFileRemove(HttpContext.Name)"></span>
</Template>
</UploaderTemplates>
<UploaderEvents ValueChange="OnChange"></UploaderEvents>
</SfUploader>
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</EditForm>
@code {
AboutUs aboutUs = new AboutUs();
private SfUploader uploadObj { get; set; }
private string base64 { get; set; }
private string fileSize { get; set; }
List<fileInfo> files = new List<fileInfo>();
private string canonicalURL { get; set; }
private List<string> uploadedFilePaths = new List<string>();
[Inject] protected ToastService ToastService { get; set; } = default!;
public class fileInfo
{
public int Id { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public double Size { get; set; }
}
protected override async Task OnInitializedAsync()
{
canonicalURL = Navigate.Uri.Split("?")[0];
aboutUs = await Http.GetFromJsonAsync<AboutUs>("/api/AboutUs");
if (aboutUs != null)
{
if (!string.IsNullOrEmpty(aboutUs.Image))
{
files.Add(new fileInfo
{
Name = aboutUs.Image,
Path = $"/uploads/{aboutUs.Image}",
Size = 0 // optionally retrieve actual size
});
uploadedFilePaths.Add(aboutUs.Image);
fileSize = "existing image";
Console.WriteLine($"Image: {aboutUs.Image}");
}
}
}
public async Task OnChange(UploadChangeEventArgs args)
{
foreach (var file in args.Files)
{
var memoryStream = new MemoryStream();
await file.File.OpenReadStream(long.MaxValue).CopyToAsync(memoryStream);
var bytes = memoryStream.ToArray();
string base64 = "data:image/png;base64," + Convert.ToBase64String(bytes);
files.Add(new fileInfo
{
Path = base64,
Name = file.FileInfo.Name,
Size = file.FileInfo.Size
});
memoryStream.Position = 0;
var content = new MultipartFormDataContent();
content.Add(new StreamContent(memoryStream), "files", file.FileInfo.Name);
var response = await Http.PostAsync("/api/AboutUs/upload", content);
if (response.IsSuccessStatusCode)
{
var savedPaths = await response.Content.ReadFromJsonAsync<List<string>>();
uploadedFilePaths.AddRange(savedPaths);
}
}
}
private async Task onFileRemove(string fileName)
{
var file = files.FirstOrDefault(f => f.Name == fileName);
if (file != null)
{
var fileInfo = new Syncfusion.Blazor.Inputs.FileInfo
{
Name = file.Name,
Size = file.Size
};
await uploadObj.RemoveAsync(new[] { fileInfo });
files.Remove(file);
}
}
private async Task Submit()
{
if (uploadedFilePaths.Count == 0)
{
ToastService.Notify(new(ToastType.Warning, "Please upload an image before submitting."));
return;
}
aboutUs.Image = uploadedFilePaths.FirstOrDefault();
var response = await Http.PutAsJsonAsync("/api/AboutUs/update", aboutUs);
if (response.IsSuccessStatusCode)
{
ToastService.Notify(new(ToastType.Success, "About Us content updated successfully."));
await Task.Delay(1500);
Navigate.NavigateTo("/aboutUs/index");
}
else
{
ToastService.Notify(new(ToastType.Danger, "Failed to update About Us content."));
}
}
}
<style>
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
align-items: start;
}
.editor-section,
.uploader-section {
width: 100%;
}
.upload-image {
max-width: 100%;
height: auto;
border-radius: 8px;
margin-bottom: 10px;
}
.file-name {
font-weight: bold;
margin-bottom: 5px;
}
.file-size {
font-size: 0.9em;
color: gray;
}
</style>
Hi mohammadelhaj,
Thank you for reaching out to us. In order to correctly display the preview image for preloaded files, you will need to add the FileInfo object, which includes the name, size, and base64-encoded file path, within the OnInitialized method. This will ensure that the preview image loads as expected for preloaded image.
Please find the code snippet below, which illustrates how to achieve this, along with the sample link for your reference:
<div class="col-lg-12 control-section"> <div class="control_wrapper"> <div class="col-lg-6" id="dropArea"> <SfUploader @ref="uploadObj" CssClass="@CssClass" AutoUpload="true" AllowedExtensions=".png, .jpg, .jpeg"> <UploaderButtons Browse="Browse"></UploaderButtons> <UploaderFiles> <UploaderUploadedFiles Name="Nature" Size=500000 Type=".png"></UploaderUploadedFiles> <UploaderUploadedFiles Name="Home" Size=500000 Type=".png"></UploaderUploadedFiles> </UploaderFiles> <UploaderTemplates> <Template Context="HttpContext"> <img class="upload-image" alt="Preview Image @(HttpContext.Name)" src="@files.FirstOrDefault(item => item.Name == HttpContext.Name)?.Path" /> <div class="name file-name" title="@HttpContext.Name">@HttpContext.Name</div> <div class="file-size">@fileSize</div> <span class="e-icons e-file-remove-btn" id="removeIcon" title="Remove" @onclick="() => onFileRemove(HttpContext.Name)"></span> </Template> </UploaderTemplates> <UploaderEvents ValueChange="OnChange"></UploaderEvents> </SfUploader> </div> </div> </div>
@code { private SfUploader uploadObj { get; set; } public string CssClass = "custom-file"; private string base64 { get; set; } private string fileSize { get; set; } List<FileInfo> files = new List<FileInfo>(); //Hidden:Lines private string canonicalURL { get; set; } // FileInfo class definition public class FileInfo { public string Name { get; set; } // File name public double Size { get; set; } // File size in bytes public string Path { get; set; } // File preview URL } protected override void OnInitialized() { canonicalURL = NavigationManager.Uri.Split("?")[0]; files.Add(new FileInfo() { Name = "Nature.png", Size = 500000, // Size in bytes Path = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWI...." // Replace with your actual file URL } ); files.Add(new FileInfo() {
Name = "Home.png", Size = 500000, // Size in bytes Path = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWI......" // Replace with your actual file URL }); } //End:Hidden public async Task OnChange(UploadChangeEventArgs args) {
foreach (var file in args.Files) { var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), "Images"); var fullPath = Path.Combine(pathToSave, file.FileInfo.Name); MemoryStream memoryStream = new MemoryStream(); using var fileStream = file.File.OpenReadStream(long.MaxValue); await fileStream.CopyToAsync(memoryStream); byte[] bytes = memoryStream.ToArray(); string base64 = "data:image/png;base64," + Convert.ToBase64String(bytes); files.Add(new FileInfo() { Path = base64, Name = file.FileInfo.Name, Size = file.FileInfo.Size });
} }
|
Regards,
Priyanka K
To be honest, it was hard to figure out how to use this.
In the API controller I save the image like this and in other endpoint to save to data base
[HttpPost("upload")]
public async Task<IActionResult> UploadImageOnly()
{
var files = Request.Form.Files;
var savedPaths = new List<string>();
foreach (var image in files)
{
string uniqueName = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
string filePath = Path.Combine(_env.WebRootPath, "uploads", uniqueName);
using var stream = new FileStream(filePath, FileMode.Create);
await image.CopyToAsync(stream);
savedPaths.Add(uniqueName);
}
return Ok(savedPaths);
}
so this save the image like this (7b0badde-c4d1-42ba-9702-9578123f3153.jpg) so I put it in the Name with aboutUs.Image and the path inside uploader folder in wwwroot in server project and size I don't think it is a big deal but it still does not work so whay is the key concept to make it work
just in case , I want when the User go to edit page he get the image he want to edit with other information and in the Uploader I want the image to be displayed and the use if he want to change it he can if he
Hi Killer,
Thank you for your patience. Here's a detailed response to help you troubleshoot and ensure the process works smoothly:
- File Upload and Storage: It seems you are correctly saving the uploaded images using a unique filename. Ensure that the directory (
/wwwroot/uploads) exists on your server and that your application has sufficient permissions to write to this directory. - Serving Static Files: Confirm that your server is configured to serve static files from the
wwwrootdirectory. In yourStartup.cs, ensure you have this configuration in place: app.UseStaticFiles(); - Display the Image: When loading the edit page, retrieve the stored image path from your database. Ensure that this path is correctly formatted as a URL relative to the server's root before passing it to the Syncfusion Uploader.
- Path and URL Accuracy: Double-check that the
UploadedFileproperty contains the correct URL relative to your server. If the images are not displaying, verify the browser’s network tab to ensure that requests to the image URL are not failing. - Testing and Debugging: Test the functionality by loading an existing image on the edit page. Try changing the image to see if it updates both in the UI and in your backend storage.
By following these steps, you should be able to implement and troubleshoot the image upload and edit feature effectively. If you encounter any specific errors or issues during this process, please let us know so we can assist further.
Regards,
Priyanka K
- 3 Replies
- 2 Participants
-
KI Killer
- Jun 6, 2025 03:56 PM UTC
- Jun 19, 2025 03:37 PM UTC