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)
AlexChow
关联项目
FreeSql QQ群:4336577
BA & Blazor QQ群:795206915
Maui Blazor 中文社区 QQ群:645660665
知识共享许可协议
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系 。
转载声明
本文来自博客园,作者:周创琳 AlexChow,转载请注明原文链接:https://www.cnblogs.com/densen2014/p/16052875.html