我花了一整天的时间试图强制浏览器打开PDF文件,而不是使用System.Web.Mvc.FileResult
下载它,并且我以旧的方式使用System.Web.Response这样做:
控制器
//StaticData.ReportsTemp it's my type of Dictionary<string,object>
public async Task<ActionResult> GenerateReport() {
//some code
var tempGuid = Guid.NewGuid().ToString();
StaticData.ReportsTemp[tempGuid] = File(strem, obj.MediaType, obj.name);
return Content(opertionGuid);
}
public FileResult DownloadReport(string fileName) {
FileResult result = null;
FileStreamResult st = null;
if (StaticData.ReportsTemp.ContainsKey(fileName)) {
st = StaticData.ReportsTemp[fileName] as FileStreamResult;
result = st;
StaticData.ReportsTemp.Remove(fileName);
if (st.ContentType == System.Net.Mime.MediaTypeNames.Application.Pdf || 1 == 1) { //Old fashion way
byte[] buff = null;
System.IO.BinaryReader br = new System.IO.BinaryReader(st.FileStream);
buff = br.ReadBytes((int) st.FileStream.Length);
Response.BinaryWrite(buff);
Response.AddHeader("content-length", buff.Length.ToString());
Response.ContentType = st.ContentType;
Response.AddHeader("Content-Disposition", "inline; filename=" + st.FileDownloadName + ";");
return null;
}
}
return result;
}
JS
function onSuccess(data, status, xhr) {
window.open("@Url.RouteUrl(new { Controller = "Main", Action = "DownloadReport" })?filename=" + xhr.responseText,'_brank');
}
我的下载过程分为两个步骤:
PDF在浏览器中打开,所有其他文件仍然只是下载。
但我仍然想知道是否还有其他方法可以实现这一目标? 有没有办法用System.Web.Mvc ActionResult的类来做到这一点?
答案 0 :(得分:1)
我不知道StaticData
班的工作方式。通常,您可以返回FileResult
,如果文件无效或不存在,您可以显示PageNotFound页面。
注意:如果客户端没有安装Acrobat,则无法强制他们在浏览器中查看。
public class ReportFile
{
public byte[] Data { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
}
public async Task<ActionResult> GenerateReport()
{
//some code
var tempGuid = Guid.NewGuid().ToString();
StaticData.ReportsTemp[tempGuid] = new ReportFile
{
Data = data, // Convert stream to byte array
ContentType = obj.MediaType,
FileName = obj.name
};
return Content(tempGuid);
}
public ActionResult DownloadReport(string fileName)
{
if (StaticData.ReportsTemp.ContainsKey(fileName))
{
ReportFile file = StaticData.ReportsTemp[fileName];
StaticData.ReportsTemp.Remove(fileName);
if (file.ContentType == MediaTypeNames.Application.Pdf)
{
var cd = new ContentDisposition { FileName = file.FileName, Inline = true };
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(file.Data, file.ContentType);
}
}
return View("PageNotFound");
}