2013-03-11 41 views
0

行動:如何使用一個actionlink下載mvc4中的多個文件?

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

你爲什麼要重新發明'FileStreamResult'較慢的版本? – SLaks 2013-03-11 13:45:42

+0

HTTP不支持。 – SLaks 2013-03-11 13:46:08

+0

如何使用'FileStreamResult'? – 2013-03-11 13:49:23

回答

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 
} 
+0

你能幫我解決這個問題嗎? – 2013-03-12 08:27:49