C# Blazor Razor组件创建pdf下载链接
几天来我一直在想这个问题,但我想不出来。如何在Blazor Razor组件中创建带有pdf本地文件url的下载链接C# Blazor Razor组件创建pdf下载链接,c#,blazor,C#,Blazor,几天来我一直在想这个问题,但我想不出来。如何在Blazor Razor组件中创建带有pdf本地文件url的下载链接 @code { string noteContent; string fileName = "note.txt"; string path = @"E:\Attachments\test.txt"; Uri myUri = new Uri(@"E:\Attachments\test.txt"); public async void DownloadFile() { //
@code {
string noteContent;
string fileName = "note.txt";
string path = @"E:\Attachments\test.txt";
Uri myUri = new Uri(@"E:\Attachments\test.txt");
public async void DownloadFile()
{
//await JSRuntime.InvokeAsync<object>(
// "FileSaveAs",
// fileName,
// noteContent
//);
await JSRuntime.InvokeAsync<object>(
"downloadURI",
myUri,
"test.txt"
);
}
}
下面是一个示例JS Interop函数,它为最终用户提供下载提示:
window.saveFile = function (bytesBase64, mimeType, fileName) {
var fileUrl = "data:" + mimeType + ";base64," + bytesBase64;
fetch(fileUrl)
.then(response => response.blob())
.then(blob => {
var link = window.document.createElement("a");
link.href = window.URL.createObjectURL(blob, { type: mimeType });
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
以下是我在Blazor应用程序中对它的称呼:
public static void Save(IJSRuntime jsRuntime, byte[] byteData, string mimeType, string fileName)
{
if (byteData == null)
{
jsRuntime.InvokeVoidAsync("alert", "The byte array provided for Exporting was Null.");
}
else
{
jsRuntime.InvokeVoidAsync("saveFile", Convert.ToBase64String(byteData), mimeType, fileName);
}
}
剩下的就是从文件中获取您的字节[]
。如何做到这一点将取决于您的用例和应用程序,以下是一些常见情况:
- 在服务器端Blazor应用程序中,您的C#已经在服务器上运行,因此您可以插入
,并从中获取webroot路径以访问您的文件-类似于IWebHostEnvironment
,然后从该路径读取。然后调用JS互操作var path=\u hostingEnvironment.WebRootPath+\\myfile.txt
- 在WASM应用程序中,您没有文件系统。因此,您需要将这些数据存储在内存中—无论您是从文件选择器获取数据,还是从某个WebAPI端点获取数据,甚至是在C#中生成数据,都取决于特定的用例
@inject IJSRuntime jsRuntime;
你可能也会发现这个非常有用的东西。谢谢你。将进行测试。非常感谢你花时间来帮助很棒!你可以接受这个答案来帮助其他人寻找这样的示例
public static void Save(IJSRuntime jsRuntime, byte[] byteData, string mimeType, string fileName)
{
if (byteData == null)
{
jsRuntime.InvokeVoidAsync("alert", "The byte array provided for Exporting was Null.");
}
else
{
jsRuntime.InvokeVoidAsync("saveFile", Convert.ToBase64String(byteData), mimeType, fileName);
}
}