0

行动:

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

4

1 回答 1

1

一种可能性是将所有文件压缩成一个文件,然后将此压缩文件返回给客户端。您的代码也有一个巨大的缺陷:您在将整个文件内容返回给客户端之前将其加载到内存中: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
}
于 2013-03-11T13:51:00.560 回答