首页 > 解决方案 > 在浏览器中下载 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");

    }

欢迎任何帮助或建议

标签: c#asp.netasp.net-mvc

解决方案


因为您在谈论浏览器,所以我假设您的 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);
    }
}

推荐阅读