c# - 在浏览器中下载 xls
问题描述
我希望浏览器显示 xls 文件已保存。怎么做?在下面的示例代码中:它将我的报告保存在正确的路径中,但浏览器未显示文件已保存。当我单击“下载报告”按钮时,返回空白页面而不是下载报告。
public ActionResult FilePathResult(List<PrintOutModel> printOutModelList )
{
Prints.Print.PrintReport.Printer print = new Prints.Print.PrintReport.Printer();
var printReport = print.CreateRender(printOutModelList);
byte[] reportResult = printReport;
string path = AppDomain.CurrentDomain.BaseDirectory +"Report9802.xls";
var fileStream = new FileStream(path,
FileMode.Create,
FileAccess.ReadWrite
);
fileStream.Write(reportResult, 0, reportResult.Length);
return new FileStreamResult(fileStream, "application/xls");
}
欢迎任何帮助或建议
解决方案
因为您在谈论浏览器,所以我假设您的 API 实现都很好,并且问题集中在前端。
这是 Angular 7 的示例代码。为了下载文件,您的 API“必须”是 POST 调用。这就是浏览器请求文件下载的方式。您基本上应该在服务上调用 postBlob 方法,该方法显然已作为本示例中HttpClient
命名的成员注入。http
由于此代码读取服务器发送的内容配置并设置动态链接,因此它创建了用户单击 XLS 文件的超链接并调用浏览器的默认下载行为的效果(提示“另存为”、自动打开等) .
希望这可以帮助 !!
public postBlob(url: string, param: any): Observable<BlobFile> {
return this.http.post<Blob>(url, param, { observe: 'response', responseType: 'blob' as 'json' }).pipe(map(r => {
return this.onBlobResponse(r);
}));
}
private onBlobResponse(r: HttpResponse<Blob>) {
const contentDisposition = r.headers.get('Content-Disposition');
const filename = contentDisposition.split(';')[1].split('filename')[1].split('=')[1].trim();
this.saveFile(filename, r.body);
return <BlobFile>{
name: filename,
blob: r.body
};
}
private saveFile(filename: string, blob: Blob) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0);
}
}
推荐阅读
- android - kotlin 语法变为 viewBinding
- google-sheets - 将单个单元格排列到 Google 表格中的整个列
- html - 访问模板中的vue环境变量
- c++ - 使用两个线程写入文件
- ios - dyld:库未加载:@rpath/AgoraAIDenoiseExtension.framework/AgoraAIDenoiseExtension 引用自
- node.js - 如何在更改 url 时保持套接字连接处于活动状态
- python - 如何从 Python 中的大图像中提取重叠块?
- assembly - 汇编中的移位字符
- vb6 - vb6 - 发送字节,接收端从 0 到 255
- flutter - 为什么这个 boxshadow 没有出现?