行动:
public ActionResult Download(string filename)
{
var filenames = filename.Split(',').Distinct();
var dirSeparator = Path.DirectorySeparatorChar;
foreach (var f in filenames)
{
if (String.IsNullOrWhiteSpace(f)) continue;
var path = AppDomain.CurrentDomain.BaseDirectory + "Uploads" + dirSeparator + f;
if (!System.IO.File.Exists(path)) continue;
return new BinaryContentResult
{
FileName = f,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(path)
};
}
return View("Index");
}
BinaryContentResult 方法:
public class BinaryContentResult : ActionResult
{
public string ContentType { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.ContentType = ContentType;
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.BinaryWrite(Content);
context.HttpContext.Response.End();
}
}
看法:
@{
foreach (var item in Model)
{
@Html.ActionLink("Link","Index", "FileUpload", new { postid = item.PostId })
}
}
但 actionlink 只下载一个(第一个)文件。