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

本文关键字:mvc4 下载 文件 一个 何使用 actionlink | 更新日期: 2023-09-27 18:03:24

操作:

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

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

一种可能性是将所有文件压缩到一个文件中,然后将该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
}