Rol*_*ain 4 c# file-upload blazor
我正在我的 blazor 服务器应用程序上测试图像上传。为此,我的.razor
组件如下所示:
@page "/uploadtest"
<h1>Upload Example</h1>
<AuthorizeView>
<Authorized>
<p>A simple example with a model, which can upload images</p>
<label>
Load Images:
<InputFile OnChange="@UploadImages" multiple accept=".jpg,.jpeg,.png" />
</label>
</Authorized>
<NotAuthorized>
<p>To use this application, please <a href="Identity/Account/Login">log in</a> or <a href="Identity/Account/Register">register</a> a new account! </p>
</NotAuthorized>
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)
我将代码隐藏在一个单独的.razor.cs
文件中,该类如下所示:
public partial class UploadExample: ComponentBase
{
#region Protected Properties
[Inject]
protected AuthenticationStateProvider AuthenticationStateProvider { get; private set; }
[Inject]
protected IWebHostEnvironment WebHostEnvironment { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// File upload
/// Only images of type .jpg and png are allowed here.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
protected async Task UploadImages(InputFileChangeEventArgs ifc)
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
try
{
string userId = user.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;
string currentTime = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
string path = Path.Combine(WebHostEnvironment.WebRootPath, $@"UserData/{userId}/UploadTest/{currentTime}");
Directory.CreateDirectory(path);
var files = ifc.GetMultipleFiles();
foreach (var file in files)
{
var filePath = Path.Combine(path, file.Name);
await using FileStream fs = new(filePath, FileMode.Create);
await file.OpenReadStream().CopyToAsync(fs);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
这是我的问题:
UploadImages()
函数执行后,应用程序悄然崩溃。我在控制台输出中找不到任何有用的东西,也没有抛出任何异常,它只是以代码-1停止。但是,文件已成功上传到预期文件夹。此外,崩溃似乎与功能无关。wwwroot
文件夹中,我确信这是一个坏主意。我已经有一个数据访问层,它是一个单独的类库,可以处理所有数据库内容。基本上,我只想要存储在数据库中的图像的路径,但数据访问库仍然应该处理图像的存储。IBrowserFile
将对象提供给单独的类库是否很常见?如果没有,数据如何发送到数据访问层?编辑 在浏览器的开发选项中,我收到以下错误:
错误:连接已断开,并出现错误“错误:WebSocket 已关闭,状态代码:1006 ()。”。
一旦我选择要上传的任何文件。我测试了不同的东西(有/没有授权、调用/不调用函数UploadImages()
等......)
我偶然发现了这个问题:Blazor Server inputfile Crashes with certain Chromium Based Browsers
这听起来很像您遇到的情况,对吧?
为了进一步证明这一理论,请下载以下代码:https://github.com/mu88/StackOverflow_BlazorServerFileUpload
这基本上是您的代码的简化副本,可以在我的机器上的 Chrome 和 Firefox 中运行。如果您可以在计算机上的 Chrome 和 Firefox 中运行该代码,但不能在 Brave 中运行,我想我们可以确定找到了罪魁祸首。
归档时间: |
|
查看次数: |
3153 次 |
最近记录: |