How to Preview Images in Syncfusion Blazor File Upload Component
Tags: blazor, csharp, dotnet, webdev
Published: 2021-01-19 11:54:20

---
title: How to Preview Images in Syncfusion Blazor File Upload Component
published: true
date: 2021-01-13 11:15:18 UTC
tags: blazor, csharp, dotnet, webdev
canonical_url: https://www.syncfusion.com/blogs/post/how-to-preview-images-in-syncfusion-blazor-file-upload-component.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/01/How-to-preview-images-in-Syncfusion-Blazor-File-Upload-component-672x372.png
---
Syncfusion Blazor [File Upload](https://www.syncfusion.com/blazor-components/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

- [Visual Studio 2019](https://visualstudio.microsoft.com/vs/)
- [.NET Core 3.0 and above](https://dotnet.microsoft.com/download/dotnet-core/3.0)
- [Blazor templates](https://docs.microsoft.com/en-us/aspnet/core/blazor/templates?view=aspnetcore-5.0)

## 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](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly/) 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](https://www.syncfusion.com/blazor-components/blazor-textbox) and [File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) components.

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

```csharp
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.

```html
<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.

```js
<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.

```html
<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.

```html
<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.

```csharp
[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.

```js
@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.

```csharp
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.

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2020/12/Image-Preview-in-File-Upload-Component-1-2.png)<figcaption>Image Preview in File Upload Component</figcaption>

## GitHub Sample

You can download the complete source code of this example from this [GitHub](https://github.com/SyncfusionExamples/blazor-file-upload-image-preview) 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](https://www.syncfusion.com/blazor-components/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](https://www.syncfusion.com/blazor-components) 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](https://www.syncfusion.com/account/manage-trials/downloads) or our [NuGet package](https://www.nuget.org/packages/Syncfusion.Blazor). Feel free to have a look at our [online examples](https://blazor.syncfusion.com/) and [documentation](https://blazor.syncfusion.com/documentation/introduction/) to explore other available features.

You can also contact us through our [support forums](https://www.syncfusion.com/forums/blazor-components), [Direct-Trac](https://www.syncfusion.com/support/directtrac/incidents/newincident), or [feedback portal](https://www.syncfusion.com/feedback/blazor-components). We are always happy to assist you!