我想要实现的是相当于这个Javascript:一个按钮,可以选择一个文件,并处理该文件。
document.querySelector("button").addEventListener("click", () => {
const input = document.createElement("input");
input.type = "file";
input.onchange = () => alert("You picked: " + input.files[0]?.name);
input.click();
});<button>Pick File</button>
我尝试创建一个InputFile,但是没有引用(Id和上下文是null的):
<div class="text-center mt-5">
<button class="btn btn-primary" @onclick="@this.AddFiles">
@("AddFiles".Loc())
</button>
</div> async Task AddFiles()
{
var input = new InputFile();
await this.Js.InvokeVoidAsync("triggerClick", input.Element);
// triggerClick is a Javascript method that click the element
}我目前的解决方法是将一个不可见的input附加到DOM中,即使这样也不太简单:
@inject IJSRuntime Js;
<div class="text-center mt-5">
<button class="btn btn-primary" @onclick="this.AddFiles">
@("AddFiles".Loc())
</button>
</div>
@if (this.fileRequested)
{
<InputFile @ref="this.txtFile" OnChange="this.OnFileChanged" class="d-none" />
} bool fileRequested = false;
InputFile? txtFile;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (this.fileRequested && this.txtFile is not null)
{
await this.Js.InvokeVoidAsync("triggerClick", this.txtFile.Element);
}
}
async Task AddFiles()
{
this.fileRequested = true;
}
async Task OnFileChanged(InputFileChangeEventArgs e)
{
this.fileRequested = false;
await this.Js.InvokeVoidAsync("alert", "You picked: " + e.File?.Name);
}发布于 2022-11-14 13:02:18
你可以试试这个:
<InputFile id="filePickerId" OnChange="this.OnFileChanged" class="d-none"></InputFile>
<label for="filePickerId">
<button type="button" style="pointer-events: none;">Pick a file</button>
</label>
async Task OnFileChanged(InputFileChangeEventArgs e)
{
await this.Js.InvokeVoidAsync("alert", "You picked: " + e.File?.Name);
}https://stackoverflow.com/questions/74429992
复制相似问题