2017-05-10 45 views
0

如何下載非靜態的pdf文件。C#MVC下載動態文件名

我嘗試這樣做:

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())); 
} 

索引視圖

<table class="table"> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.CreatedInvoice) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.InvoicePath) 
     </th> 
     <th></th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.CreatedInvoice) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.InvoicePath) 
     </td> 
     <td> 
@Html.ActionLink("Download", "GetPdf", new { id = item.InvoicePath }) 
</td> 
</tr> 
} 
</table> 

這是我上傳文件的方法

public ActionResult fileupload(HttpPostedFileBase file) 
     { 
      if (file != null) 
      { 

       string ImageN = System.IO.Path.GetFileName(file.FileName);//get the file path 
       string physicalPath = Server.MapPath("~/Invoice/" + ImageN);//store the file path in a folder called img 

       file.SaveAs(physicalPath); 

       Invoice newP = new Invoice(); 
       newP.InvoicePath = ImageN; 
       newP.CreatedInvoice = DateTime.Now; 
       db.Invoices.Add(newP);//store the image path in a database 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      return View(); 
     } 

任何建議,將不勝感激

+0

您使用發票.ToString()創建路徑 - 你是否重寫Invoice對象的ToString()方法返回路徑?你能看到正在生成的路徑嗎? –

回答

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 }) 

真的不知道爲什麼上面的方法不起作用

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文件名,這是所有你需要提供服務的文件反正。

當文件上傳時,您正在將文件名保存在InvoicePath屬性中,您應該使用此屬性來獲取要下載的文件的名稱。

+0

好,所以我沒有嘗試,因爲你張貼,但我得到錯誤0x80070002,請求的URL \t http://本地主機:11809 /發票/ GetPdf /簡單遞增標記rubric.pdf,物理路徑\t C:\ Users \ JephyDa1st \ Desktop \ Ds3Doc \ Ds3Project \ Supp \ Supp \ Supp \ Invoices \ GetPdf \ Brief遞增標記rubric.pdf –

+0

您的GetPdf方法確實受到影響,對嗎? – sachin