如何使用一个actionlink下载mvc4中的多个文件?

时间:2013-03-11 13:45:01

标签: c# asp.net-mvc asp.net-mvc-4

动作:

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只下载一个(fisrt)文件。

1 个答案:

答案 0 :(得分:1)

一种可能性是将所有文件压缩到一个文件中,然后将此zip文件返回给客户端。此外,您的代码存在一个巨大的缺陷:您在将整个文件内容返回到客户端之前将其加载到内存中:System.IO.File.ReadAllBytes(path)而不是仅使用专为此目的而设计的FileStreamResult。你似乎用BinaryContentResult类重新发明了一些轮子。

所以:

public ActionResult Download(string filename)
{
    var filenames = filename.Split(',').Distinct();
    string zipFile = Zip(filenames);
    return File(zip, "application/octet-stream", "download.zip");
}

private string Zip(IEnumerable<string> filenames)
{
    // here you could use any available zip library, such as SharpZipLib
    // to create a zip file containing all the files and return the physical
    // location of this zip on the disk
}