In the last Blazor asp core post, we discussed CRUD operations in the Blazor server app without Entity Framework in Blazor Server App.
In this asp core post, we will discuss how we can upload and display images in Blazor App basically we want to Preview an image before it is uploaded.
So let’s start
Add Blazor component in your project
and copy paste the below code.
and copy paste the below code.
@page "/uploadandpreviewimage"
<h3>UploadandPreviewImage</h3>
<div>
<div class="row">
<InputFile OnChange="@OnFileUploadChange" class="form-control" accept="image/png,image/jpeg" />
</div>
<br />
<div class="row">
<img src="@ImageDataUri" style="width:150px">
</div>
<br />
<button type="submit" class="btn btn-success btn-ui" @onclick="() => SaveImage()">Save Image</button>
</div>
@code {
public IBrowserFile ImageFile { get; set; }
public string ImageDataUri { get; set; }
[Inject]
public IWebHostEnvironment Environment { get; set; }
protected async Task SaveImage()
{
if (ImageFile != null)
{
var trustedFileNameForFileStorage = Guid.NewGuid() + ".jpg";
string path = Environment.WebRootPath + "/images/";
if (!Directory.Exists(Path.Combine(path)))
{
Directory.CreateDirectory(path);
}
var imagePath = Path.Combine(path, trustedFileNameForFileStorage);
await using FileStream fs = new(imagePath, FileMode.Create);
await ImageFile.OpenReadStream(1024 * 10000).CopyToAsync(fs);
}
}
public async Task OnFileUploadChange(InputFileChangeEventArgs e)
{
try
{
var file = e.GetMultipleFiles().FirstOrDefault();
if (file != null)
{
ImageFile = file;
var format = "image/jpg";
var imageFile = await file.RequestImageFileAsync(format, 640, 480);
var fileStream = imageFile.OpenReadStream((1024 * 10000));//max file size//1MB is equal to 1000KB
var mediaStream = new MemoryStream();
await fileStream.CopyToAsync(mediaStream);
var dataUri = "data:" + format + ";base64," + Convert.ToBase64String(mediaStream.ToArray());
ImageDataUri = dataUri;
}
}
catch (Exception ex)
{
}
}
}
In above code in OnFileUploadChange function, I’m reading the file from InputFileChangeEventArgs and then I’m converting the file data into to base64 data image for showing the image in HTML ui page.
We using the html InputFile Blazor component control to read browser file data into .NET code. The InputFile Blazor component renders an HTML <input /> element of type file. By default, the user selects single files.
The above InputFile component executes the OnFileUploadChange method when the OnChange (change) event triggers. An InputFileChangeEventArgs give access to the uploaded file list and file information of each file: