c# - 下载要生成的报告文件到客户端
问题描述
我正在使用下面的代码来创建和下载 Telerik 报告。
var reportName = "../api/Templates/Invoice.trdp";
var reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
var reportSource = new Telerik.Reporting.UriReportSource()
{
Uri = reportName
};
reportSource.Parameters.Add("ID", 3);
reportSource.Parameters.Add("Username", "demouser");
var deviceInfo = new System.Collections.Hashtable()
{
{"DocumentTitle", "Annual Report" }
};
var result = reportProcessor.RenderReport("PDF", reportSource, deviceInfo);
if (!result.HasErrors)
{
System.IO.File.WriteAllBytes(System.IO.Path.ChangeExtension(reportName, "pdf"), result.DocumentBytes);
}
}
一旦我将它托管在服务器中,它就会在服务器端创建文件。如何在不在服务器中创建任何文件的情况下将其下载到客户端计算机中。
解决方案
我可以通过使用返回类型将文件返回给客户端来做到这一点HttpResponseMessage
public HttpResponseMessage GenerateOrderReport(int orderID)
{
var reportName = ConfigurationManager.AppSettings["EmailAttachmentURLTemplate"];
string activeDir = ConfigurationManager.AppSettings["EmailAttachmentSaveLocation"];
string newPath = System.IO.Path.Combine(activeDir, ConfigurationManager.AppSettings["EmailAttachmentSaveFolder"]);
var reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
var reportSource = new Telerik.Reporting.UriReportSource()
{
Uri = reportName
};
reportSource.Parameters.Add("OrderID", 141);
reportSource.Parameters.Add("OrderMethodTypeID", 2);
var deviceInfo = new System.Collections.Hashtable()
{
{"DocumentTitle", "Order Report" }
};
var result = reportProcessor.RenderReport("PDF", reportSource, deviceInfo);
if (!result.HasErrors)
{
System.IO.Directory.CreateDirectory(newPath);
string newFileName = "OrderReport.pdf";
newPath = System.IO.Path.Combine(newPath, newFileName);
FileStream fileStream = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite);
fileStream.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
fileStream.Close();
HttpResponseMessage fileResult = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(newPath, FileMode.Open);
fileResult.Content = new StreamContent(stream);
fileResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
fileResult.Content.Headers.ContentDisposition.FileName = newFileName;
return fileResult;
}
else
{
throw new Exception("Report contains errors. " + result.Errors[0].Message);
}
}
推荐阅读
- c - 使用单个 nChannel 将 IplImage 转换为 SDL_Surface
- dagger-2 - Android:创建bundle的新实例并在mvp的匕首中传递给意图
- css - 如何获得 sass 过滤器的结果颜色:在特定的十六进制颜色上饱和()?
- google-bigquery - 如果我的浏览器崩溃/计算机关闭,BigQuery 是否会使用目标表完成长时间运行的作业?
- php - Mailchimp API (PHP) - 您的广告系列尚未准备好发送
- java - 在java中计算数组中的重复次数
- xamarin - 在 Xamarin 表单中禁用连字
- pandas - 将字符串系列转换为数字一
- sql-server - 在 SQL Server 中运行 SELECT 时缺少行
- asp.net-core - 使用控制台应用在 Gitlab 上持续集成