从 Blazor 使用 JSInterop 读取输入文件

Reading input file with JSInterop from Blazor

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

然而,当从 Blazor - JSRuntime 调用它时,出现以下错误:

'Cannot read property 'files' of undefined
TypeError: Cannot read property 'files' of undefined

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); 
    }
}

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);
        }

P.S 所以根据错误,该方法被成功调用但它收到一个 undefined.Do 当我使用 InvokeAsync?

时我需要做一个转换或其他东西

我需要获取文件的内容。

哥们,你为什么把传给fileChange函数的参数当作一个事件对象来处理?它不是。再看看你的代码,ev.Value 不是事件对象。它是文件名的字符串值。试试这个:

window.methods = {
    fileChange:function(fileName) {

        console.log("file retrieved: " + fileName);

 }
}

希望这对您有所帮助...

您可以使用 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());

        }
    }

}