如何修复我的 Blazor 服务器应用程序文件下载过程?

时间:2021-06-26 14:41:55

标签: javascript blazor-server-side

我正在构建 Blazor 服务器应用程序 .net5 ,我正在使用以下代码下载文件:

//After button click
else if(buttonName == "Download")
        {

            JSRuntime.InvokeVoidAsync("downloadFromUrl", new { Url = "api/files", FileName = "test.pdf" });

        }

//this is the function for the download proccess
    function downloadFromUrl(options) {
        var _a;
        var anchorElement = document.createElement('a');
        anchorElement.href = options.url;
        anchorElement.download = (_a = options.fileName) !== null && _a !== void 0 ? _a : '';
        anchorElement.click();
        anchorElement.remove();
    }
    //# sourceMappingURL=helper.js.map

上面的一半工作,我开始下载但我下载的文件已损坏,大小 该文件与原始文件相比要小得多,没有错误我可以在这里发布,我不 了解可能出了什么问题,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不确定是否使用 InvokeVoidAsync,假锚是理想的。这是另一种方法。

创建一个中间件。在 Startup.cs 上方的 UseStaticFiles() 中注册它。 在中间件的 Invoke 中,检索 rawUrl

string rawUrl = context.Request.Path.ToString() + context.Request.QueryString.ToString();

如果在这个 rawUrl 中,您识别出文件下载的 URL,则对其进行处理并返回。否则await _next(context);

过程(我写“处理它”的地方)将是:

byte[] bytes = System.IO.File.ReadAllBytes("..."); // or anything else, e.g. the bytes come from a DB
context.Response.ContentType = "application/pdf"; // should be adapted to the file type
context.Response.Headers.Add("Content-Disposition", "attachment; filename=\"myFileName.pdf\"; size=" + bytes.Length.ToString());
context.Response.Body.WriteAsync(bytes);

在 HTML 源代码中,您不必创建带有点击处理程序的按钮。只需放置一个锚点,中间件识别出一个 HREF。

中间件信息:https://docs.microsoft.com/en-us/dotnet/architecture/blazor-for-web-forms-developers/middleware,参见自定义中间件

相关问题