仅允许在Blazor中上载特定文件类型 [英] Allow only specific file type to upload in blazor

查看:12
本文介绍了仅允许在Blazor中上载特定文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BlazorInputFile包在Blazor中上载文件。

问题

此代码不起作用。

<InputFile OnChange="OnFileUpload" accept="image/x-png,image/jpeg" title="Upload jpeg or png image" />

如何限制用户在Blazor中只能上传jpeg或png?如果需要更多材料来支持这个问题,请让我知道。

推荐答案

我有一个指向Steve Sanderson的InputFiles的包装器,该包装器具有AllowweExtenses属性。 这是一个事后筛选器,这意味着用户必须上传文件,然后您告诉他们不允许文件扩展名。关于Pre Upload的方式有很多线程,至少很难说。

上传后我是这样做的:

Nuget:DataJguer.Blazor.FileUpload

包括Blazor示例项目的完整源代码位于以下位置:

https://github.com/DataJuggler/BlazorFileUpload

最相关的部分总结如下:

使用DataJguer.Blazor.FileUpload

<FileUpload CustomSuccessMessage="Your file uploaded successfully." 
    OnReset="OnReset" ResetButtonClassName="localbutton" ShowStatus="false"
    PartialGuidLength="10" MaxFileSize=@UploadLimit FilterByExtension="true" 
    ShowCustomButton="true"  ButtonText="Start" OnChange="OnFileUploaded"
    CustomButtonClassName="startbutton" ShowResetButton="false" 
    AppendPartialGuid="true" AllowedExtensions=".jpg;.png;"
    CustomExtensionMessage="Only .jpg and .png files are allowed." 
    InputFileClassName="customfileupload" Visible=false
    FileTooLargeMessage=@FileTooLargeMessage>
</FileUpload>

请注意条件扩展和CustomExtensionMessage的两个属性。

以下是我处理FileUploaded:

的相关代码部分
// Create a new instance of a 'FileInfo' object.
FileInfo fileInfo = new FileInfo(file.Name);

// I don't know if it's even possible for an extension to be upper case
uploadedFileInfo.Extension = fileInfo.Extension.ToLower();

// if FilterByExtension is true and the AllowedExtensions text exists
if ((FilterByExtension) && (!String.IsNullOrWhiteSpace(AllowedExtensions)))
{
    // verify the extension exists
    if (!String.IsNullOrWhiteSpace(fileInfo.Extension))
    {
        // If the allowed extensions // fixed issue where uploading 
        abort = !AllowedExtensions.ToLower().Contains(fileInfo.Extension.ToLower());
    }
    else
    {
        // you must have an extension
        abort = true;
    }
}

也许这会给你一些启发。

如果你想看到使用它的实时站点,我几天前刚刚发布了以下内容: https://pixeldatabase.net-使用BQL-位图查询语言编辑图像

这篇关于仅允许在Blazor中上载特定文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆