![](/img/trans.png)
[英]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.