从 ASP.NET Core api 从 Blazor 客户端应用程序下载文件

Jea*_*ser 5 c# client webassembly asp.net-core blazor

我创建了一个返回FileStreamResult对象的 ASP.NET Core api 控制器。(如果需要,我可以更改结果类型)

Get函数的代码如下:

[HttpGet("[action]/{p_gInspectionID}/{p_nIndex}")]
public async Task<FileStreamResult> GetInspectionPictureToDownload(Guid p_gInspectionID, int p_nIndex)
{
  var l_strFilePath = await GetPictureFilePathAsync(p_gInspectionID, p_nIndex);

  using (var l_sReader = System.IO.File.OpenRead(l_strFilePath))
  {
    return (File(l_sReader, "image/jpeg"));
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要在 Blazor (Webassembly) 客户端应用程序中使用这个结果。

我的目标是有一个按钮来在用户点击文件时在浏览器中启动文件的下载

这应该会启动浏览器的下载功能。是否可以在 Blazor 客户端应用程序中实现这一点?

Jea*_*ser 5

这是我解决问题的方法。事实上,解决方案非常简单。感谢@Data Juggler 为我指明了正确的方向。

我的 Blazor 解决方案包含两个项目:

  • 服务器端 API(Blazor 服务器)
  • 客户端 (Blazor WebAssembly)。

这是服务器端的代码:

[AllowAnonymous]
[HttpGet("[action]/{p_strPictureFilePath}")]
public IActionResult GetInspectionPicture(string p_strPictureFilePath)
{
  var l_sReader = System.IO.File.OpenRead(p_strPictureFilePath);

  return (File(l_sReader, "application/octet-stream", Path.GetFileName(p_strPictureFilePath)));
}
Run Code Online (Sandbox Code Playgroud)

...以及客户端的代码:

在文件中添加此脚本client-shared.js

window.downloadInspectionPicture = function (p_strServerFilePath)
{
  var link = document.createElement('a');
  link.href = 'api/Data/GetInspectionPicture/' + this.encodeURIComponent(p_strServerFilePath);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
Run Code Online (Sandbox Code Playgroud)

当然,对该文件的引用存在于index.html

  <script src="client-shared.js"></script>
Run Code Online (Sandbox Code Playgroud)

最后,在 razor 文件中添加一个链接,并在单击链接时调用脚本:

<a href="javascript:void(0)" @onclick="@(async () => await DownloadPictureAsync())">Download</a>

@code
{
  [Inject]
  IJSRuntime ThisJSRuntime { get; set; }

  private async Task DownloadPictureAsync()
  {
    await ThisJSRuntime.InvokeVoidAsync("downloadInspectionPicture", ServerFilePath);
  }
}
Run Code Online (Sandbox Code Playgroud)

希望我的回答很清楚并且对某人有用


StP*_*lis 5

我试图做同样的事情,但我的 API 已获得授权,因此在阅读本文后,最终在 Web 程序集应用程序中下载字节,并使用 JavaScript 从字节下载文件。

function downloadFromByteArray(options: { 
  byteArray: string, 
  fileName: string, 
  contentType: string
}): void {

  // Convert base64 string to numbers array.
  const numArray = atob(options.byteArray).split('').map(c => c.charCodeAt(0));

  // Convert numbers array to Uint8Array object.
  const uint8Array = new Uint8Array(numArray);

  // Wrap it by Blob object.
  const blob = new Blob([uint8Array], { type: options.contentType });

  // Create "object URL" that is linked to the Blob object.
  const url = URL.createObjectURL(blob);

  // Invoke download helper function that implemented in 
  // the earlier section of this article.
  downloadFromUrl({ url: url, fileName: options.fileName });

  // At last, release unused resources.
  URL.revokeObjectURL(url);
}
Run Code Online (Sandbox Code Playgroud)