我在报告控制器中使用以下方法。它成功返回我分配给数据库中varBinary(MAX)字段的文件内容。我的问题是,当此代码执行时,它会导致浏览器提示用户保存或打开文件。我想阻止这种情况发生。
如何强制它仅将二进制数据返回给调用控制器方法而不将结果推送到客户端浏览器?
private FileContentResult RenderReportFile(LocalReport localReport, List<ReportDataSource> listDS, string sFilename, string sReportType, bool bLandscape)
{
string sHeight = "11";
string sWidth = "8.5";
if (bLandscape)
{ sWidth = sHeight; sHeight = "8.5"; }
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = sReportType;
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + sReportType + "</OutputFormat>" +
" <PageWidth>" + sWidth + "in</PageWidth>" +
" <PageHeight>" + sHeight + "in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + sFilename + "." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
return File(renderedBytes, "application/pdf", sFilename + "." + fileNameExtension);
}
答案 0 :(得分:1)
此代码负责将文档发送给客户端:
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + sFilename + "." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
将其删除,系统不会提示用户进行保存或打开。