Blazor元件自做九: 用20行程式碼實現檔案上傳,瀏覽目錄功能 (3)
接上篇 Blazor元件自做九: 用20行程式碼實現檔案上傳,瀏覽目錄功能 (2)
7. 使用配置檔案指定監聽地址
開啟 appsettings.json
檔案,加入一行
"UseUrls": "http://localhost:8000;http://0.0.0.0:8000;",
完整檔案如下
{ "UseUrls": "http://localhost:8000;http://0.0.0.0:8000;", //加入這句 "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
開啟Program.cs檔案,在 var builder = WebApplication.CreateBuilder(args);
之後加入一句 builder.WebHost.UseUrls(builder.Configuration["UseUrls"]);
完整Program.cs程式碼
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using BlazorFileUpload.Data; using Microsoft.Extensions.FileProviders; using System.Text.Encodings.Web; var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseUrls(builder.Configuration["UseUrls"]); //加入這句 // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton<WeatherForecastService>(); //設定檔案上傳的大小限制 , 預設值128MB builder.Services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = long.MaxValue; }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); var dir = Path.Combine(app.Environment.WebRootPath, "Upload"); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); var opt = new DirectoryBrowserOptions { FileProvider = new PhysicalFileProvider(dir), Formatter = new AME.HtmlDirectoryFormatterChsSorted(HtmlEncoder.Default), RequestPath = new PathString("/Upload") }; app.UseDirectoryBrowser(opt); app.UseRouting(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); app.Run();
8. 一些錦上添花的小處理
獲取本機IP,生成外部連結按鈕分發複製給移動裝置用. 腦洞一下可以擴充套件二維碼掃碼上傳等功能.
LocalIP.cs
using System.Net; using System.Net.Sockets; namespace BlazorFileUpload { public class LocalIP { public static string GetLocalIp() { //得到本機名 string hostname = Dns.GetHostName(); //解析主機名稱或IP地址的system.net.iphostentry例項。 IPHostEntry localhost = Dns.GetHostEntry(hostname); if (localhost != null) { foreach (IPAddress item in localhost.AddressList) { //判斷是否是內網IPv4地址 if (item.AddressFamily == AddressFamily.InterNetwork) { return item.MapToIPv4().ToString(); } } } return "0.0.0.0"; } } }
獲取本機區域網IP string? ip = LocalIP.GetLocalIp();
從配置檔案分離埠號 string? port = Config!["UseUrls"].ToString().Split(';')[0].Split(':')[2];
Index.razor 新增外部地址按鈕
<a class="btn btn-primary" href="@($"http://{ip}:{port}")" target="_blank">
<span class="oi oi-browser" aria-hidden="true"></span> 外部地址
</a>
完整Index.razor程式碼
@page "/"
<PageTitle>BlazorFileUpload</PageTitle>
<div>
上傳檔案(Max100)
<InputFile OnChange="OnChange" style="max-width:400px" class="form-control" multiple />
</div>
<div style="padding-top:20px">
上傳圖片
<InputFile OnChange="OnChange" style="max-width: 400px" class="form-control" multiple accept='image/*' />
</div>
<div style="padding-top:30px">
<a class="btn btn-primary" href="Upload">
<span class="oi oi-file" aria-hidden="true"></span> 瀏覽檔案
</a>
<a class="btn btn-primary" href="@($"http://{ip}:{port}")" target="_blank">
<span class="oi oi-browser" aria-hidden="true"></span> 外部地址
</a>
</div>
<pre>
<code>
@uploadstatus
</code>
</pre>
<button class="btn btn-info" @onclick="(()=>help=!help)">說明</button>
@if (help)
{
<pre>
你的IP @ip
<code>
配置:
appsettings.json 檔案
自由修改監聽ip和埠
"UseUrls": "@Config!["UseUrls"]" //預設 "http://localhost:8000;https://0.0.0.0:8000;"
</code>
</pre>
}
@code{
[Inject] protected Microsoft.AspNetCore.Hosting.IWebHostEnvironment? HostEnvironment { get; set; }
[Inject] protected IConfiguration? Config { get; set; }
protected string UploadPath = "";
protected string? tempfilename = null;
protected bool displayProgress;
protected string? uploadstatus;
long maxFileSize = 1024 * 1024 * 15;
string? ip;
string? port;
bool help;
protected override void OnAfterRender(bool firstRender)
{
if (!firstRender) return;
UploadPath = Path.Combine(HostEnvironment!.WebRootPath, "Upload");
if (!Directory.Exists(UploadPath)) Directory.CreateDirectory(UploadPath);
ip = LocalIP.GetLocalIp();
try
{
port = Config!["UseUrls"].ToString().Split(';')[0].Split(':')[2];
}
catch
{
port = "8000";
}
StateHasChanged();
}
protected async Task OnChange(InputFileChangeEventArgs e)
{
int i = 0;
var selectedFiles = e.GetMultipleFiles(100);
foreach (var item in selectedFiles)
{
i++;
await OnSubmit(item);
uploadstatus += Environment.NewLine + $"[{i}]: " + item.Name;
}
}
protected async Task OnSubmit(IBrowserFile efile)
{
if (efile == null) return;
var tempfilename = Path.Combine(UploadPath, efile.Name);
await using FileStream fs = new(tempfilename, FileMode.Create);
using var stream = efile.OpenReadStream(maxFileSize);
displayProgress = true;
await stream.CopyToAsync(fs);
displayProgress = false;
StateHasChanged();
}
}
9. 寫在最後
這個小工程單檔案框架依賴打包win-x64平臺999KB,壓縮分發280KB,香不香.
國內環境有相當大一批人一直不願意接觸 .Net5, .Net6 總守著老的技術不放,不願意接受新的改變,現在.Net生態環境變得越來越開發越來越順手,再加上Blazor這個新事物,還有什麼可以猶豫的呢?跟著我們一起玩玩Blazor吧!
10. 專案原始碼
https://github.com/densen2014/Blazor100
https://gitee.com/densen2014/Blazor100
AME.SortedDirectoryChs庫
https://gitee.com/densen2014/Densen.Extensions/tree/master/HtmlDirectoryFormatterExtensions
Blazor元件自做九: 用20行程式碼實現檔案上傳,瀏覽目錄功能 (1)
Blazor元件自做九: 用20行程式碼實現檔案上傳,瀏覽目錄功能 (2)