[英]How can I generate a downloadable c# class from within an ASP.NET MVC website?
[英]How do I link to downloadable files in ASP.NET MVC?
我是ASP.NET MVC的新手,我試圖鏈接到可下載的文件(.zip,.mp3,.doc等)。
我有以下視圖: ProductName
映射到: http://domain/ProductName
我有一個.zip
文件,必須映射到URL http://domain/ProductName/Product.zip
我在哪里將此.zip
文件放在MVC文件夾結構中?
如何在MVC中添加此.zip
文件的鏈接? 是否有這樣做的Url。*方法?
您可以使用FilePathResult或Controller.File方法。
protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName) {
return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };
}
示例代碼操作方法。
public ActionResult Download(){
return File(fileName,contentType,downloadFileName);
}
希望這段代碼。
以下類將一個文件DownloadResult
添加到您的程序中:
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(string name)
{
return new DownloadResult
{ VirtualPath = "~/files/" + name, FileDownloadName = name };
}
注意虛擬路徑,它是站點根目錄中的文件目錄; 這可以更改為您想要的任何文件夾。 這是您放置文件以供下載的地方。 查看本教程,了解如何為ASP.NET MVC編寫自定義文件下載操作結果
使用FileResult作為takepara的另一個簡化示例如上所述。
注意我創建了一個HelperController.cs類。
在你看來......
@Html.ActionLink("Link Description", "Download", "Helper", new { fileName = "downloaded_file_name.ext", path = "root path location to your file" }, null)
控制器動作......
public FileResult Download(string fileName, string path)
{
var webRootPath = Server.MapPath("~");
var documentationPath = Path.GetFullPath(Path.Combine(webRootPath, path));
var filePath = Path.GetFullPath(Path.Combine(documentationPath, fileName));
return File(filePath, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.