使用 JSInterop 从 Blazor 读取输入文件

Ber*_*ian 1 javascript interop blazor

您好,我正在尝试使用 api 从本地存储加载文件FileReader。我已经js直接在HTML页面中测试了该方法并且它有效。

Blazor但是,当从-调用它时,JSRuntime我收到以下错误:

'Cannot read property 'files' of undefined
TypeError: Cannot read property 'files' of undefined
Run Code Online (Sandbox Code Playgroud)

JS

window.methods = {
    fileChange:function(event) {
        var file = event.target.files[0];
        console.log("file retrieved");
        var reader = new FileReader();
        reader.onload = function (event) {
            console.log(reader.result);
        };
        reader.readAsText(file); 
    }
}
Run Code Online (Sandbox Code Playgroud)

CSHTML

<input  type="file" onchange="@(async(x)=>await onFileChange(x))"/>
public async Task onFileChange(UIChangeEventArgs ev) {
            var str=await JSRuntime.Current.InvokeAsync<string>("methods.fileChange", ev.Value);
        }
Run Code Online (Sandbox Code Playgroud)

PS 所以根据错误,该方法被成功调用,但它收到一个未定义的消息。使用时我需要进行强制转换还是其他操作吗InvokeAsync

我需要获取文件的内容。

Ed *_*eau 5

您可以使用 JavaScript 互操作来解决这个问题。已经有 NuGet 包可用于处理此问题。有关答案的现场视频演示,请参阅我的视频https://www.youtube.com/watch?v=-IuZQeZ10Uw&t=12s

在视频中,名为 Blazor.FileReader 的 NuGet 包用于 JavaScript 互操作。使用 Blazor.FileRead,我能够读取input创建数据 URI 并将其上传到 Azure 认知服务。您可以看到下面的代码。

@using Blazor.FileReader
@using System.IO;
@using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
@using Newtonsoft.Json;

@page "/fetchdata"
@inject HttpClient Http
@inject IFileReaderService fileReaderService;

<h1>Cognitive Services Vision</h1>

<input type="file" id="fileUpload" ref="fileUpload" onchange="@UploadFile" />

<img src="@imageData" style="@( analysis != null ? $"border: 5px solid #{analysis.Color.AccentColor}" : "" )" />

@if (analysis == null)
{
    <p>Select an image</p>
}
else
{
    <p>@analysis.Description.Captions.First().Text</p>
    <p>@analysis.Color.AccentColor</p>
    <ul>
        @foreach (var tag in analysis.Tags)
        {
            <li>@tag.Name</li>
        }
    </ul>
}
@functions {

    ElementRef fileUpload;
    string imageData = String.Empty;
    ImageAnalysis analysis;

    async Task UploadFile()
    {
        var files = await fileReaderService.CreateReference(fileUpload).EnumerateFilesAsync();

        using (MemoryStream memoryStream = await files.First().CreateMemoryStreamAsync())
        {
            byte[] bytes = memoryStream.ToArray();

            imageData = $"data:image/jpg;base64,{Convert.ToBase64String(bytes)}";
            var response = await Http.PostAsync(
                    requestUri: "api/SampleData/Save",
                    content: new ByteArrayContent(bytes)
                );
            analysis = JsonConvert.DeserializeObject<ImageAnalysis>(await response.Content.ReadAsStringAsync());

        }
    }

}
Run Code Online (Sandbox Code Playgroud)