Downloading of zip file through ASP.NET MVC using DotNetZip

前端 未结 5 907
小蘑菇
小蘑菇 2020-12-03 04:03

I have created a text file in a folder and zipped that folder and saved @same location for test purpose. I wanted to download that zip file directly on user machine after it

5条回答
  •  我在风中等你
    2020-12-03 04:34

    For those just wanting to return an existing Zip file from the App_Data folder (just dump in your zip files there), in the Home controller create this action method:

        public FileResult DownLoad(string filename)
        {
            var content = XFile.GetFile(filename);
            return File(content, System.Net.Mime.MediaTypeNames.Application.Zip, filename);
    
        }
    

    Get File is an extention method:

       public static byte[] GetFile(string name)
        {
            string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
            string filenanme = path + "/" + name;
            byte[] bytes = File.ReadAllBytes(filenanme);
            return bytes;
        }
    

    Home controller Index view looks like this:

    @model  List
    
    
    
        @foreach (var item in Model)
        {
            
        }
    
    @Html.DisplayName("File Name") @Html.DisplayName("Last Write Time") @Html.DisplayName("Length (mb)")
    @Html.ActionLink("DownLoad","DownLoad",new {filename=item.Name}) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.LastWriteTime) @Html.DisplayFor(modelItem => item.Length)

    The main index file action method:

        public ActionResult Index()
        {
            var names = XFile.GetFileInformation();
            return View(names);
        }
    

    Where GetFileInformation is an extension method:

        public static List GetFileInformation()
        {
            string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
            var dirInfo = new DirectoryInfo(path);
            return dirInfo.EnumerateFiles().ToList();
        }
    

提交回复
热议问题