1
我需要爲我的用戶提供一個文件,該文件可能是pdf或xls文件。MVC4允許用戶下載文件的最簡單方法是什麼(pdf)
我似乎找不到一個簡單的方法來做到這一點。
這就是我今天來Pu有:
public FileResult DownloadPDF()
{
return view("/download/pdf1");
}
我需要爲我的用戶提供一個文件,該文件可能是pdf或xls文件。MVC4允許用戶下載文件的最簡單方法是什麼(pdf)
我似乎找不到一個簡單的方法來做到這一點。
這就是我今天來Pu有:
public FileResult DownloadPDF()
{
return view("/download/pdf1");
}
最快的方法是做這樣的事情:
public ActionResult DownloadPdf()
{
return File("~/Download/pdf1.pdf", "application/pdf", Server.UrlEncode("NameOfFile.pdf"));
}
最佳和最快的方式,我發現:
public void DownloadReport(string path)
{
// Clear the content of the response
Response.ClearContent();
FileInfo newFile = new FileInfo(path);
string fileName = Path.GetFileNameWithoutExtension(newFile.Name) + DateTime.Now + newFile.Extension;
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
// Add the file size into the response header
Response.AddHeader("Content-Length", newFile.Length.ToString());
// Set the ContentType
Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(newFile.FullName);
// End the response
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
//send statistics to the class
}
將文件的路徑傳遞給此方法&根據您的文件更改內容類型e類型。
我怎樣才能讓下載文件的名稱爲「TESTPDF1」? – user3086989
像這樣:return File(「〜/ Download/pdf1.pdf」,「application/pdf」,Server.UrlEncode(「TESTPDF1.pdf」)); – mmilan