2015-10-23 112 views
1

我想创建zip文件供用户下载并将该文件可以是任何文件,如图像或文本文件获取错误等当创建压缩文件下载

我想创建一个zip文件,下载它在我的锚点标签点击事件。

我有我的数据库表中的3个文件是这样的:

https://my.net/storage/log.txt

https://my.net/storage/log1.txt

https://my.net/storage/log2.txt

这是我的代码:

public ActionResult DownloadImagefilesAsZip() 
{ 
    string documentUrl = repossitory.GetDocumentsUrlbyId(id);//output:https://my.net/storage/log.txt, 
https://my.net/storage/log1.txt, 
https://my.net/storage/log2.txt, 


    if (!string.IsNullOrEmpty(documentUrl)) 
      { 
       string[] str = documentUrl.Split(','); 
       if (str.Length > 1) 
       { 
        return new ZipResult(str); 
       } 
      } 
    } 



public class ZipResult : ActionResult 
    { 
     public string[] Filename1 { get; private set; } 

     public ZipResult(string[] str) 
     { 
      Filename1 = str; 
     } 

     public override void ExecuteResult(ControllerContext context) 
     { 
      if (context == null) 
      { 
       throw new ArgumentNullException("context"); 
      } 

      var response = context.HttpContext.Response; 
      response.ContentType = "application/gzip"; 
      using (var zip = new ZipFile()) 
      { 
       foreach (string t in Filename1) 
       { 
        if (!string.IsNullOrEmpty(t)) 
        { 
         zip.AddFile(t); 
        } 
       } 
       //zip.AddDirectory(Path); 
       zip.Save(response.OutputStream); 
       var cd = new ContentDisposition 
       { 
        FileName = "Images.Zip", 
        Inline = false 
       }; 
       response.Headers.Add("Content-Disposition", cd.ToString()); 
      } 
     } 
    } 

错误:给定的路径的格式不低于行支持:

zip.AddFile(t); 
+0

cting zip?那是什么意思? – DavidG

+1

库是否支持将HTTPS URL传递给AddFile()?如果这是你正在使用的:http://dotnetzip.herobo.com/DNZHelp/html/b1d9ff87-214d-d219-af0c-8075512cb3a9.htm它说“它应该指文件系统中的文件” –

+0

@DavidG :对不起没有让你 –

回答

1

Zip需要根据您的机器链接到您的文件,但是您要给它的远程URL。所以,你的情况将会有两个步骤:

  1. 首先下载文件到您的服务器
  2. 邮编他们和客户与它

响应查找下面这样的样本。我已经尝试过并且有效。

public ActionResult Index() 
{ 
    var destination = Server.MapPath("~/Downloads/144_ctrl.txt"); 
    var fileUrl = "http://textfiles.com/computers/144_ctrl.txt";   

    using (var web = new WebClient()) 
    using (var zip = new ZipFile()) 
    { 
     web.DownloadFile(new Uri(fileUrl), destination); 

     zip.AddDirectory(Server.MapPath("~/Downloads")); 
     MemoryStream output = new MemoryStream(); 
     zip.Save(output); 
     return File(output, "application/zip", "sample.zip"); 
    } 
} 
相关问题