我生成我的MVC應用程序的報告女巫然後出口到PDF和女巫然後保存在我的~/Reports/Invoices/
目錄。我想逐一下載這些文件。文件下載MVC
這裏是我的類:
public class DownloadResult : ActionResult
{
public DownloadResult()
{
}
public DownloadResult(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath
{
get;
set;
}
public string FileDownloadName
{
get;
set;
}
public override void ExecuteResult(ControllerContext context) {
if (!String.IsNullOrEmpty(FileDownloadName)) {
context.HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=" + this.FileDownloadName);
}
string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
context.HttpContext.Response.TransmitFile(filePath);
}
}
,這裏是我的控制器操作:
public ActionResult Download(int id)
{
return new DownloadResult
{
VirtualPath = "~/Reports/Invoices/" + Table.Where(x => x.ID == id).FirstOrDefault().ID + ".pdf",
FileDownloadName = Table.Where(x => x.ID == id).FirstOrDefault().ID.ToString()
};
}
當我嘗試使用此代碼它是所有填充符號就像當你的局部視圖嘗試在記事本中打開一個二進制文件。
我在做什麼錯的任何想法?
我已經試過這樣:
public FileResult Download(int id)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Reports/Invoices/" + Table.Where(x => x.ID == id).FirstOrDefault().ID + ".pdf"));
string fileName = Table.Where(x => x.ID == id).FirstOrDefault().ID.ToString();
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}
,並得到相同的結果
Invoices.GridLoadDone = function() {
$.contextMenu({
selector: '#gbox_invoiceGrid',
callback: function (key, options) {
var m = "clicked: " + key;
switch (key) {
case "view":
Globals.PerformAjaxFromHyperlink(null, '#/Invoice/View/' + Invoices.CurrentRow, true, Invoices.CurrentRow);
Globals.SetUrl('#/Invoice/View/' + Invoices.CurrentRow, false);
return true;
break;
case "email":
Globals.PerformAjaxFromHyperlink(null, '/Invoice/Email/' + Invoices.CurrentRow, false);
break;
case "download":
Globals.PerformAjaxFromHyperlink(null, '/Invoice/Download/' + Invoices.CurrentRow, false);
//$("#readingsGrid").jqGrid('editRow', Readings.CurrentRow,
break;
}
},
items: {
"view": {
name: "View Invoice"
},
"email": {
name: "Email Invoice"
},
"download": {
name: "Download Invoice"
},
}
});
你爲什麼要重新創造'File()'helper和'FileResult'類? – SLaks
你能告訴我如何用File()和FileResult類來做這件事嗎?我以前沒有與這方面的任何工作。 – Hydro
不是一個確切的重複,但看看http://stackoverflow.com/questions/3604562/download-file-of-any-type-in-as-net-mvc-using-fileresult – Yuck