如何使用Blazor呈现知道其内容类型的字节数组



以下代码对应于Blazor服务器端页面:

<pre>
@page "/ShowFile/{Id:guid}"

//// What to put here to let the browser render the byte array stored on this.Model
//// Also how to specify the content type of the response?

@code
{
[Parameter]
public Guid Id { get; set; }

private byte[] Model { get; set; }

protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
//// Gets the byte array of a file based on its identifier.
this.Model = await this.GetFile(this.Id).ConfigureAwait(false); 
}
}
</pre>
In ASP.NET MVC I used to do it in the controller action as:
<pre>
this.Response.ContentType = "application/pdf"; //// Assuming that byte array represents a PDF document.
await this.Response.Body.WriteAsync(this.Model);
</pre>

我该怎么做才能让浏览器根据其内容类型在页面中呈现字节数组?

@page "/test"
@inject HttpClient Http
@if (!string.IsNullOrEmpty(pdfContent))
{
<embed src="@pdfContent" width="800px" height="2100px" />
<iframe src="@pdfContent" width="800px" height="2100px" />
<object data="@pdfContent" width="500" height="200"></object>
}

@code {
string pdfContent = "";
protected async override Task OnInitializedAsync()
{
var data = await Http.GetByteArrayAsync("the source you pdf");
pdfContent = "data:application/pdf;base64,";
pdfContent += System.Convert.ToBase64String(data);
}
}

我在客户端blazor上试过这个,它在那里有效。尝试一下服务器端。

我从Zsolt Bendes的回答中设法在服务器端Blazor上实现了这一点。一旦我得到Base64字符串,我就必须使用StateHasChanged((重新呈现页面。

@page "/Document/Open/{documentId:int}"
@if (!string.IsNullOrEmpty(pdfContent))
{
<embed src="@pdfContent" width="800px" height="2100px" />
<iframe src="@pdfContent" width="800px" height="2100px" />
<object data="@pdfContent" width="500" height="200"></object>
}

@code {
[Parameter]
public int DocumentId { get; set; }
string pdfContent = "";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var apiService = await CreateClient();
var data = await apiService.Open(DocumentId);
pdfContent = "data:application/pdf;base64,";
pdfContent += System.Convert.ToBase64String(data);
StateHasChanged();
}
}
}

第一次呈现页面时,我创建了一个服务实例,该实例的构造函数中包含一个HTTP客户端。然后我调用方法Open,它从Azure Blob存储返回字节数组。

相关内容

  • 没有找到相关文章

最新更新