Search code examples
blazorblazor-server-sideblazor-client-sideasp.net-blazor

Allow only specific file type to upload in blazor


I am using BlazorInputFile package for uploading file in Blazor.

Problem

This code does not work.

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

How to restrict user to only upload jpeg or png in Blazor? Please let me know if more stuff is required to support the question.


Solution

  • I have a wrapper to Steve Sanderson's InputFile that has an AllowedExtensions property. This is an after the fact filter, meaning the user has to upload the file and then you tell them that file extension isn't allowed. There are entire threads on doing the pre upload way, and it is difficult to say the least.

    This is the way I did it after the upload:

    Nuget: DataJuggler.Blazor.FileUpload

    The full source code including a Blazor sample project is located here:

    https://github.com/DataJuggler/BlazorFileUpload

    The most relevant part is summarized here:

    using DataJuggler.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>
    

    Notice the two properties for AllowedExtensions, and CustomExtensionMessage.

    Here is the relevant part of code where I handle the 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;
        }
    }
    

    Maybe this will give you some ideas.

    If you want to see a live site that uses it, I just published this a couple of days ago: https://pixeldatabase.net - Edit Images with BQL - Bitmap Query Language