MatBlazor
MatBlazor copied to clipboard
MatFileUpload how to filter file extension?
I want the upload file to accept only "pdf" file, like:
How can I do that?
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};
@oblin , Please let me know if this does not help.
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.
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.