我正在用blazor学习C#,我想知道如何验证类型文件的输入,这样它就不允许大于3MB 的文件
此示例解释了如何使用InputFile组件以Blazor上传文件(svg格式(。请注意变量maxFileSize,该变量设置流可提供的最大字节数。
文件上传.razor.cs
private bool fileUploading;
private string filePath = "C:\fileFolder\file.svg";
private const int maxFileSize= 3 * 1024 * 1024; //3MB max size
private async Task UploadSvgFileAsync(InputFileChangeEventArgs e)
{
fileUploading = true;
try
{
string fileExtension = Path.GetExtension(e.File.Name);
if (!fileExtension.Equals(".svg", StringComparison.OrdinalIgnoreCase))
throw new Exception("SVG file is required.");
var stream = e.File.OpenReadStream(maxFileSize);
await using FileStream fs = new(filePath, FileMode.Create);
await stream.CopyToAsync(fs);
}
catch (Exception ex)
{
//some error handling
}
fileUploading = false;
}
在您的FileUpload.razor组件中:
@if (fileUploading )
{
<span>- File Uploading...</span>
}
<InputFile OnChange="@UploadSvgFileAsync" />
我建议阅读以下文章,了解如何正确使用Blazor应用程序中的文件:
文件上传
文件下载
FileInfo file = new FileInfo(yourFile);
获取文件字节大小:
var fileBytes = file.Length;
将字节转换为MB:
var fileMBs = fileBytes / (1024*1024);