创建要下载的zip文件时出错

时间:2015-10-23 11:16:38

标签: asp.net-mvc download dotnetzip

我正在尝试创建供用户下载的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);

1 个答案:

答案 0 :(得分:1)

Zip希望根据您的计算机链接到您的文件,但是您要为其提供远程网址。因此,在您的情况下,将有两个步骤:

  1. 首先将文件下载到您的服务器
  2. 拉链并用它回复客户
  3. 在下面找到一个示例。我已经尝试过并且有效。

    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");
        }
    }
    
相关问题