Upload Files Using InputFile Component In Blazor
Index.razor:
@page "/"
@using System.IO
@inject IWebHostEnvironment env
<h1>File Upload!</h1>
<InputFile OnChange="OnInputFileChange" multiple />
<button class="btn btn-sm btn-success" type="button" @onclick="FileUpload2">Upload</button>
<label>@labelText</label>
<br />
<div class="image-list">
<table class="table table-bordered">
<tr>
@foreach (var imageDataUrl in imageDataUrls)
{
<td>
<img src="@imageDataUrl" />
</td>
}
</tr>
</table>
</div>
@code {
IList<string> imageDataUrls = new List<string>();
IReadOnlyList<IBrowserFile> selectedImages;
public string labelText = "";
async Task OnInputFileChange(InputFileChangeEventArgs e)
{
var imageFiles = e.GetMultipleFiles();
selectedImages = imageFiles;
var format = "image/png";
foreach (var imageFile in imageFiles)
{
var resizedImageFile = await imageFile.RequestImageFileAsync(format, 100, 100);
var buffer = new byte[resizedImageFile.Size];
await resizedImageFile.OpenReadStream().ReadAsync(buffer);
var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
imageDataUrls.Add(imageDataUrl);
// FileUpload(imageFiles);
}
this.StateHasChanged();
}
public async void FileUpload(IReadOnlyList<IBrowserFile> imageFile)
{
foreach (var file in imageFile)
{
Stream stream = file.OpenReadStream();
var path = $"{env.WebRootPath}\\Images\\{file.Name}";
FileStream fs = File.Create(path);
await stream.CopyToAsync(fs);
stream.Close();
fs.Close();
}
}
public async void FileUpload2()
{
foreach (var file in selectedImages)
{
Stream stream = file.OpenReadStream();
var path = $"{env.WebRootPath}\\Images\\{file.Name}";
FileStream fs = File.Create(path);
await stream.CopyToAsync(fs);
stream.Close();
fs.Close();
}
labelText = "Upload Success!";
this.StateHasChanged();
}
}
0 Comments