从Blazor读取输入文件,JSInterop

问题描述 投票:0回答:2

您好,我试图加载从使用FileReader API本地存储的文件。我已经直接在js页面测试HTML方法和它的作品。

然而从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做投什么?

我需要获得文件的内容。

javascript interop blazor
2个回答
1
投票

您可以使用JavaScript互操作性展示来解决这个问题。目前已经有处理这个包的NuGet。要知道答案的现场视频演示,请看到我的视频https://www.youtube.com/watch?v=-IuZQeZ10Uw&t=12s

在视频中使用JavaScript的互操作一个NuGet包称为Blazor.FileReader。随着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());

        }
    }

}

1
投票

老弟,你为什么把传递参数给fileChange功能,如果它是一个事件对象?它不是。在你的代码再看看,ev.Value不是事件对象。这是文件名的字符串值。试试这个:

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

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

 }
}

希望这可以帮助...

© www.soinside.com 2019 - 2024. All rights reserved.