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 は 1 つの (最初の) ファイルをダウンロードするだけです。

4

1 に答える 1

1

1つの可能性は、すべてのファイルを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
}
于 2013-03-11T13:51:00.560 に答える