目标
将blazor webassembly中的数据打包成字符串,导出csv文件,浏览器自动下载csv文件(其他文件格式思路类似)。
通过Server web api方式行不通
在server上创建controller, 返回 IActionResult 或者 FileResult
public async Task<IActionResult> Download(string id) {
Stream stream = await {{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/csv"); // returns a FileStreamResult
}
无论返回IActionResult 还是 FileResult(强制客户端下载),response均为字符串,不提示下载文件。
通过js互操作,可行
在互操作js文件中增加方法:
contentAsFile : function (filename, filetype, fileContent) {
var link = document.createElement('a');
link.download = filename;
link.href = "data:" + filetype + ";charset=utf-8," + encodeURIComponent(fileContent);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
然后在互操作类中,增加对应的C#方法:
public static async Task ContentAsFile(this IJSRuntime jsRuntime, string filename, string filetype, string fileContent)
{
await jsRuntime.InvokeAsync<Size>("contentAsFile", filename, filetype, fileContent);
}
最后,在blazor.razor中调用:
await JsRuntime.ContentAsFile(fileName+".csv", "application/csv", "\ufeff" + sb.ToString());
其中,"\ufeff"+的作用是将csv格式字符串(逗号隔开),转成Excel可读取的BOM格式。