MatBlazor icon indicating copy to clipboard operation
MatBlazor copied to clipboard

MatFileUpload how to filter file extension?

Open oblin opened this issue 4 years ago • 4 comments

I want the upload file to accept only "pdf" file, like:

How can I do that?

oblin avatar Dec 14 '20 04:12 oblin

Make your upload method, just like per the documentation, and then in the upload method specify the file extension of what you allow. If it is not of type .pdf, you could use the toaster to display a message to your user indicating the file type is not valid in that context

IMatFileUploadEntry file) { if (file?.Name.EndsWith(PdfExtension) != true) return $"The file should have a {PdfExtension};

Christian-Oleson avatar Dec 14 '20 09:12 Christian-Oleson

@oblin , Please let me know if this does not help.

CSOleson avatar Dec 15 '20 15:12 CSOleson

Could you add support for accept attribute. It's a native feature of <input type="file"...>

<input type="file"
       id="avatar" name="avatar"
       accept="image/png, image/jpeg">

or

<input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

With this approach, when file browser opens, invalid files are disabled. That way user can easily notice files that can be uploaded in the first place and that's not something we can achieve with custom upload method.

There's still an issue with drag and drop feature, where wrong file type can still be dragged onto input file. So yeah we would still need custom upload method.

codeabilly avatar Apr 01 '21 22:04 codeabilly

Instead of using the MatFileUpload out of the box you can implement your own by inheriting from BaseMatFileUpload, like so -

@inherits BaseMatFileUpload

<div @ref="@Ref" @attributes="@Attributes" class="@ClassMapper.AsString()" style="@StyleMapper.AsString()" id="@Id">
    <input type="file" @ref="@InputRef" multiple="@AllowMultiple" accept="@Accept" />
    <div class="mat-file-upload-content">
        <span>@Label</span>
        <MatIcon>@MatIconNames.Attach_file</MatIcon>
    </div>
    @if (ProgressTotal != 0)
    {
        <MatProgressBar Class="mat-file-upload-progress" Progress="@(Math.Round((double)ProgressProgress / ProgressTotal, 2))"/>
    }
</div>

@code
{
    [Parameter]
    public string Accept { get; set; } = "*";
}

This is the same as MatFileUpload.razor, except with the added Accept parameter. It does solve the immediate need, but is perhaps not the most maintainable of solutions.

SpookySurprise avatar Feb 09 '22 12:02 SpookySurprise