Is this the best way for Blazor to upload files?

Is this the best way for Blazor to upload files?

Blazor has to say that it is really a good thing, which greatly improves development efficiency. Many page interactive functions can be implemented with only a small amount of code, and they are still implemented without js. You have never thought that Blazor implements file uploads How simple it is!

最后更新 3/16/2022 7:36 AM
懒得勤快
预计阅读 5 分钟
分类
Blazor
标签
.NET Blazor upload files Blazor Server

Blazor has to say that it is really a good thing, which greatly improves development efficiency. Many page interactive functions can be implemented with only a small amount of code, and they are still implemented without js. You have never thought that Blazor implements file uploads How simple it is!

Let's start with the conclusion: It's really easy for Blazor to implement file uploading with progress display! Picture the effect:

It took less than 50 lines of code to implement such a small function. Let me share the implementation case with you.

首先引入Tewr.Blazor.FileReader包,这个包能够提供文件上传的流式读取,这样便可以实现在服务端对上传文件进行一边上传一遍写文件的操作。

Configure dependency injection (webmaster's note: This is Blazor Server mode, please check the warehouse documentation at the end of the document for wasm mode):

services.AddFileReaderService();

Next, let's layout the page first, which is very simple, and then declare two variables to display progress and display pictures:

<input type="file" /><button>上传文件</button>
<div>
  @if (!string.IsNullOrEmpty(_src)) {
  <img src="@_src" width="600px" />
  } else {
  <p>@progress</p>
  }
</div>

Then inject the IFileReaderService service into the component

@using Tewr.Blazor.FileReader @inject IFileReaderService fileReaderService;

In order for the file box to interact with C#code, you need to refer it through ElementReference:

<input @ref="inputTypeFileElement" type="file" /><button>上传文件</button>
<div>
  @if (!string.IsNullOrEmpty(_src)) {
  <img src="@_src" width="600px" />
  } else {
  <p>@progress</p>
  }
</div>
@code { private ElementReference inputTypeFileElement; private string _src;
private string progress; }

The button is bound to the event. After the button is triggered, the file stream is read through the fileReaderService. The next step is the regular binary data copy operation, which can get the transfer progress of the file. After calculation, it can be displayed on the page

<button @onclick="ReadFile">上传文件</button>
public async Task ReadFile()
{
    _src = "";
    foreach (var file in await fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync())
    {
        await using var fileStream = await file.OpenReadAsync();
        var buffer = new byte[2048];
        var finalBuffer = new byte[fileStream.Length];
        int count;
        int totalCount = 0;
        while ((count = await fileStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
        {
            Buffer.BlockCopy(buffer, 0, finalBuffer, totalCount, count);
            totalCount += count;
            progress = "文件上传中 " + (int)(totalCount * 100.0 / fileStream.Length) + "%";
            StateHasChanged();
        }
        _src = $"data:image/jpg;base64,{Convert.ToBase64String(finalBuffer)}";
        progress = "";
        StateHasChanged();
    }
}

The complete code is as follows:

@page "/counter" @using Tewr.Blazor.FileReader @inject IFileReaderService
fileReaderService;

<input @ref="inputTypeFileElement" type="file" />
<button @onclick="ReadFile">上传文件</button>
<div>
  @if (!string.IsNullOrEmpty(_src)) {
  <img src="@_src" width="600px" />
  } else {
  <p>@progress</p>
  }
</div>

@code { private ElementReference inputTypeFileElement; private string _src;
private string progress; public async Task ReadFile() { _src = ""; foreach (var
file in await
fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync()) {
await using var fileStream = await file.OpenReadAsync(); var buffer = new
byte[2048]; var finalBuffer = new byte[fileStream.Length]; int count; int
totalCount = 0; while ((count = await fileStream.ReadAsync(buffer, 0,
buffer.Length)) != 0) { Buffer.BlockCopy(buffer, 0, finalBuffer, totalCount,
count); totalCount += count; progress = "文件上传中 " + (int)(totalCount * 100.0
/ fileStream.Length) + "%"; StateHasChanged(); } _src =
$"data:image/jpg;base64,{Convert.ToBase64String(finalBuffer)}"; progress = "";
StateHasChanged(); } } }

** Webmaster interrupted: **

文章首图演示的是一张不到1MB的图片,因为Tewr.Blazor.FileReader这个包提供文件上传的流式读取,上传大文件也是可以的,下面这是上传一个34.2MB的 ZIP 压缩包,Blazor 服务端模式:

The demo is not very good. Maybe the gif can't see anything. It's just to prove that this package is really good. To upload large files, you can increase the read size of the single package above, for example: 512KB:

var buffer = new byte[1024*512];

If you look at the Microsoft Blazor file below to upload documents and change the size of the single package to greater than 20KB, the page may get stuck, and then the page will automatically refresh and reset the upload operation. However, there is no such problem when using this package. This package is very nice.

OK, this article is over

** Reference **

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 11/6/2024

Why is my blog site back in Blazor?

The blog website has gone through hardships in development. It has tried nearly 10 versions such as MVC, Vue, and Go. Now it has returned to Blazor and adopts static SSR. The speed has skyrocketed and it has been successfully launched.

继续阅读
同分类 / 同标签 2/29/2024

Data display can also be done in Winform

In the process of developing winform, data display functions are often needed. I have been using the gridcontrol before. Today, I want to use an example to introduce to you how to use the table component in ant design blazor hybrid to display data.

继续阅读
同分类 / 同标签 2/29/2024

Can Winform's interface become better?

A few days ago, I introduced to you the use of blazor hybrid in winform, and I also said that with blazor's ui, our winform program design can be more beautiful. Next, I want to use an example of drawing in winform blazor hybrid to illustrate it, hoping to be helpful to you.

继续阅读