C#MVC下载动态文件名

时间:2017-05-10 08:16:52

标签: c# asp.net-mvc

如何下​​载非静态的pdf文件。

我试过了:

contentType: "application/x-www-form-urlencoded; charset=UTF-8"

索引视图

$.ajax({
    url: '/api/submit-form',
    type: 'POST',
    data: $form.serialize(),
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", 
   ....
});

这是我的上传文件方法

public ActionResult GetPdf(string filename)
{
   var invoice = db.Invoices.ToList().Find(x=>x.InvoicePath==filename);
   return File("~/Invoice/" +invoice.ToString(), "application/pdf",Server.UrlEncode(invoice.ToString()));
}

任何建议都将非常感谢

2 个答案:

答案 0 :(得分:0)

这是您的代码应该是:

public ActionResult GetPdf(string filename)
{
   var invoice = db.Invoices.FirstOrDefault(x=> x.InvoicePath == filename);
   return File("~/Invoice/" + invoice.InvoicePath, "application/pdf", Server.UrlEncode(invoice.InvoicePath));
}

我不确定你为什么要查询数据库,因为你在paramater中得到了fileName,而且无论如何你都需要提供文件。

您在上传文件时将文件名保存在InvoicePath属性中,您应该使用此属性来获取要下载的文件的名称。

答案 1 :(得分:0)

我刚刚将下载方法更改为

 public ActionResult GetPdf(int id)
        {
            var invoice = db.Invoices.Find(id);

            return File("~/Invoice/" + invoice.InvoicePath, "application/pdf", Server.UrlEncode(invoice.InvoicePath));
        }

并将行动链接更改为

 @Html.ActionLink("Download", "GetPdf", new { id = item.InvoiceId })

真的不知道为什么上面的方法不起作用

相关问题