如何使用Blazor渲染知道其内容类型的字节数组? [英] How to render byte array knowing its content-type using Blazor?
本文介绍了如何使用Blazor渲染知道其内容类型的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码对应于Blazor服务器端页面:
The following code corresponds to a Blazor server-side page:
@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);
}
}
在ASP.NET MVC中,我曾经在控制器操作中这样做:
In ASP.NET MVC I used to do it in the controller action as:
this.Response.ContentType = "application/pdf"; //// Assuming that byte array represents a PDF document.
await this.Response.Body.WriteAsync(this.Model);
如何使浏览器根据其内容类型在页面中呈现字节数组?
What can I do to let the browser to render the byte array in my page based on its content types?
推荐答案
@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上尝试过此方法,并且在此起作用.在服务器端尝试一下.
I tried this with client side blazor and it works there. Give it a try with server side.
这篇关于如何使用Blazor渲染知道其内容类型的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文