DEV Community

Cover image for How to Preview Images in Syncfusion Blazor File Upload Component
Suresh Mohan for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

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 () 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; }
    }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
        }
Enter fullscreen mode Exit fullscreen mode

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 }
                };

        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
Enter fullscreen mode Exit fullscreen mode

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));
       }
   }
}
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)