确保文件可用并确保已授予适当的权限以访问该文件。
在服务器端,为了允许文件下载,需要添加以下代码:
public async Task DownloadVSDXFile()
{
var fileContent = await System.IO.File.ReadAllBytesAsync("file.vsd");
return File(fileContent, "application/vnd.visio", "file.vsd");
}
在客户端,使用以下代码来下载文件:
async Task DownloadFile()
{
var response = await Http.GetAsync("DownloadVSDXFile");
if (response.IsSuccessStatusCode)
{
var contentDisposition = response.Content.Headers.ContentDisposition.ToString();
var fileName = contentDisposition.Substring(contentDisposition.IndexOf("filename=") + 10).Trim('"');
var fileContent = await response.Content.ReadAsByteArrayAsync();
await JSRuntime.InvokeVoidAsync("BlazorDownloadFile",
fileName, Convert.ToBase64String(fileContent));
}
}
添加以下 JavaScript 功能以将文件保存到本地:
window.BlazorDownloadFile = (fileName, fileContent) => {
const link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = 'data:application/octet-stream;base64,' + fileContent;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
使用以上代码,你应该能够成功地在 Blazor 服务端应用程序中从服务器下载 .vsdx 文件,并将其保存到用户的本地机器中。