Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (149).NET Core  (24)Angular  (42)ASP.NET  (48)ASP.NET Core  (56)ASP.NET MVC  (84)Azure  (28)Blazor  (70)DocIO  (18)Essential JS 2  (67)Essential Studio  (161)Flutter  (82)JavaScript  (140)Microsoft  (101)PDF  (54)React  (31)Succinctly series  (120)Syncfusion  (457)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (26)Webinar  (17)Windows Forms  (54)WPF  (106)Xamarin  (117)XlsIO  (22)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (104)Chart  (43)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (3)DataGrid  (36)Development  (245)Doc  (7)DockingManager  (1)eBook  (91)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (16)Extensions  (9)File Manager  (3)Gantt  (7)Gauge  (5)Git  (3)Grid  (25)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (183)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (19)Performance  (2)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (19)SfDataGrid  (8)Silverlight  (21)Sneak Peek  (14)Solution Services  (2)Spreadsheet  (4)SQL  (5)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (9)Tips and Tricks  (42)UI  (102)Uncategorized  (68)Unix  (2)User interface  (66)Visual State Manager  (1)Visual Studio  (16)Visual Studio Code  (8)Web  (158)What's new  (102)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
How to preview images in Syncfusion Blazor File Upload component

How to Preview Images in Syncfusion Blazor File Upload Component

Syncfusion Blazor File Upload is a component for uploading one or more files, images, documents, audio, video, and other files to a server. It is an extended version of the HTML5 upload component (<input type=”file”>) with a rich set of features that includes multiple file selection, progress bars, auto-uploading, drag and drop, folder (directory) uploading, file validation, and more.

In this blog post, you will learn how to show a preview of images before uploading them in an edit form using the Syncfusion Blazor File Upload component with simple code examples.

Image upload with preview support

Image preview is an important feature in an edit form. With this feature, we can check the image before uploading it to ensure the correctness of the image we are about to upload. Implementation of the image preview feature in the Syncfusion Blazor File Upload component is very easy.

Let’s see just how easy it is to configure and display a preview image in the image tag with the Blazor File Upload component!

Prerequisites

Steps to enable image preview feature in Blazor File Upload

Create an ASP.NET Core-hosted Blazor WebAssembly (WASM) application

Let’s create a Blazor WebAssembly app and add the required model and controller classes first. Now, we have three project files created inside this solution:

  • Client: Contains the client-side code and the pages that will be rendered in the browser.
  • Server: Contains the server-side code, such as DB-related operations and web API.
  • Shared: Contains the shared code that can be accessed at both the client and server side.

Add File Upload component and configure the edit form

Here, we are going to design an Art Competition Entry Form with Syncfusion TextBox and File Upload components.

Step 1: Create a new model class inside the Data folder with the name UserDetails.

public class UserDetails
    {
        [Required]
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        [EmailAddress]
        public string Email { get; set; }
    }

Step 2: After creating the model class, access it inside the index.razor component under the pages folder. Add the following code to include the EditForm component in the application. This will create an EditContext that tracks the fields that are modified in the form and also tracks the validation messages.

<EditForm OnValidSubmit="@Submit">
</EditForm>

Step 3: Now, create an instance of the UserDetails class to bind it to the EditForm like in the following code example.

<EditForm Model="@userDetails" OnValidSubmit="@Submit">
</EditForm>

@code {
    private UserDetails userDetails = new UserDetails();
}

Step 4: Next, add data annotation validation to the First name, Last name, and Email text boxes in the EditForm.

<div class="d-flex justify-content-center align-items-center container ">
    <EditForm Model="@userDetails" OnValidSubmit="@Submit">
        <DataAnnotationsValidator />
        <h2 class="h3 mb-3 font-weight-normal">Art Competition Entry Form</h2>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label>First Name :</label>
                <SfTextBox @bind-Value="@userDetails.FirstName"></SfTextBox>
                <ValidationMessage For="@(() => userDetails.FirstName)"></ValidationMessage>
            </div>
            <div class="form-group col-md-4">
                <label>Last Name :</label>
                <SfTextBox @bind-Value="@userDetails.LastName"></SfTextBox>
                <ValidationMessage For="@(() => userDetails.LastName)"></ValidationMessage>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-10">
                <label class="col-form-label">Email ID :</label>
                <SfTextBox @bind-Value="@userDetails.Email"></SfTextBox>
                <ValidationMessage For="@(() => userDetails.Email)"></ValidationMessage>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-10">
                <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
            </div>
        </div>
    </EditForm>
</div>

Step 5: Now, add the File Upload component with a template to design the image tag for the preview, and also to show the file upload and remove icon inside the HTML table element.

<div class="form-row">
            <div class="form-group col-md-10 control-section">
                <label class="col-form-label">Upload Image:</label>
                <SfUploader ID="UploadFiles" AllowedExtensions=".png,.jpeg,.jpg">
                    <UploaderEvents ValueChange="onChange" OnRemove="onRemove"></UploaderEvents>
                    <UploaderTemplates>
                        <Template Context="HttpContext">
                            <table>
                                <tr>
                                    <td>
                                        <img class="upload-image" alt="Preview Image @(HttpContext.Name)"
                                             src="@(files.Count >0 ? files.Where(item=>item.Name == HttpContext.Name)?.FirstOrDefault()?.Path : string.Empty)">
                                    </td>
                                    <td>
                                        <div style="padding: 7px;">
                                            <h5 title="@(HttpContext.Name)">@(HttpContext.Name)</h5>
                                            <i>@(HttpContext.Size) Bytes</i>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                            <span class="e-icons e-file-remove-btn remove" id="removeIcon" title="Remove"></span>
                            <span class="e-upload-icon e-icons e-file-remove-btn" title="Upload" id="iconUpload" @onclick="@uploadFile"></span>
                        </Template>
                    </UploaderTemplates>
                </SfUploader>
            </div>
        </div>

Step 6: Then, add the Save action controller in the SampleDataController file under the Server project. Here, we have saved the file as FileStream in the given location.

[HttpPost("[action]")]
        public async Task<string> Save()
        {
            string path = string.Empty;
            if (HttpContext.Request.Form.Files.Any())
            {
                foreach (var file in HttpContext.Request.Form.Files)
                {
                    path = Path.Combine(environment.ContentRootPath, "uploads", file.FileName);
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }
            byte[] ByteArray = System.IO.File.ReadAllBytes(path);

            return Convert.ToBase64String(ByteArray);
        }

Step 7: Get the selected image files in the change event and add the fileInfo list collections in it so that it can be passed to the Save action controller for performing the upload action.

@code {
    private UserDetails userDetails = new UserDetails();
    public MultipartFormDataContent content;
    public string responseStr;
    public HttpResponseMessage filepath { get; set; }
    List<fileInfo> files = new List<fileInfo>();

    public class fileInfo
    {
        public string Path { get; set; }
        public string Name { get; set; }
        public double Size { get; set; }
    }

    public void onChange(UploadChangeEventArgs args)
    {
        files = new List<fileInfo>();
        foreach (var file in args.Files)
        {
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), "Images");
            var fullPath = Path.Combine(pathToSave, file.FileInfo.Name);
            byte[] bytes = file.Stream.ToArray();
            string base64 = Convert.ToBase64String(bytes);
            files.Add(new fileInfo() { Path = @"data:image/" + file.FileInfo.Type + ";base64," + base64, Name = file.FileInfo.Name, Size = file.FileInfo.Size });
            content = new MultipartFormDataContent {
                    { new ByteArrayContent(file.Stream.GetBuffer()), "\"upload\"", file.FileInfo.Name }
                };

        }
    }
}

Step 8: Then, add the file upload icon click event and call the save controller action in the event handler like in the following code example.

public async Task uploadFile(MouseEventArgs args)
    {
        filepath = await Http.PostAsync("https://localhost:44395/api/SampleData/Save", content);
        this.responseStr = await filepath.Content.ReadAsStringAsync();
    }

Step 9: Finally, add the OnRemove event in the File Upload component to remove the selected file from the saved location.

public void onRemove(RemovingEventArgs args)
{
   foreach (var removeFile in args.FilesData)
   {
       if (File.Exists(Path.Combine(@"\Images", removeFile.Name)))
       {
          File.Delete(Path.Combine(@"\Images\", removeFile.Name));
       }
   }
}

When executing the project, we’ll get the output like in the following screenshot. See how it displays the image preview in the File Upload view.

Image Preview in File Upload Component
Image Preview in File Upload Component

GitHub Sample

You can download the complete source code of this example from this GitHub repository.

Conclusion

I hope now you know how to easily add and display an image preview feature in your edit form with the Syncfusion Blazor File Upload component. This feature will help you ensure an image and its quality before uploading it in your edit form. You can also easily customize the preview using the template option.

So, try out the procedure provided in this blog post and leave your feedback in the comments section below.

Syncfusion’s Blazor suite offers over 65 high-performance, lightweight, and responsive UI components for the web, including file-format libraries, in a single package. Use them to build charming web applications!

Try our Blazor components by downloading a free 30-day trial or our NuGet package. Feel free to have a look at our online examples and documentation to explore other available features.

You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top