ASP.NET Web Api 2实现多文件打包并下载文件的实例

所属分类: 网络编程 / ASP.NET 阅读数: 233
收藏 0 赞 0 分享

最近由于工作和个人事务,站点也好久没更新了,但这并不影响我对.NET的热情。站点的更新工作还是得想办法抽时间来完成的。

今天利用中午的时间来写一篇关于Asp.Net Web Api下载文件的文章,之前我也写过类似的文章,请见:《ASP.NET(C#) Web Api通过文件流下载文件的实例

本文以这篇文章的基础,提供了ByteArrayContent的下载以及在下载多个文件时实现在服务器对多文件进行压缩打包后下载的功能。

关于本文中实现的在服务器端用.NET压缩打包文件功能的过程中,使用到了一个第方类库:DotNetZip,具体的使用将在正文中涉及。好了,描述了这么多前言,下面我们进入本文示例的正文。

1.首先创建名为:WebApiDownload的Web Api 项目(C#);

2.接着新建一个空的控制器,命名为:DownloadController;

3.创建一些打包文件和存放临时文件的文件夹(downloads),具体请看本文最后提供的示例项目代码

4.打开NuGet程序包管事器,搜索DotNetZip,如下图:

https://cdn.zhanzhang360.cn/imgupload/006845/2016062309583710.png

搜索到DotNetZip安装包后,进行安装,以便用于本项目将要实现多文件打包压缩的功能,如下图:

https://cdn.zhanzhang360.cn/imgupload/006845/2016062309583711.png

安装完成DotNetZip包后,我们就可以退出NuGet程序包管理器了,因为本项目为示例项目,不需再添加其他的包。

5.在Models文件夹下创建一个示例数据的类,名为:DemoData,其中的成员和实现如下:

using System.Collections.Generic;


namespace WebApiDownload.Models
{
 public class DemoData
 {
  public static readonly List<List<string>> Contacts = new List<List<string>>();
  public static readonly List<string> File1 = new List<string>
  {
   "f_1_test_1@example.com",
   "f_1_test_2@example.com",
   "f_1_test_3@example.com",
   "f_1_test_4@example.com",
   "f_1_test_5@example.com"
  };
  public static readonly List<string> File2 = new List<string>
  {
   "f_2_test_1@example.com",
   "f_2_test_2@example.com",
   "f_2_test_3@example.com",
   "f_2_test_4@example.com",
   "f_2_test_5@example.com"
  };
  public static readonly List<string> File3 = new List<string>
  {
   "f_3_test_1@example.com",
   "f_3_test_2@example.com",
   "f_3_test_3@example.com",
   "f_3_test_4@example.com",
   "f_3_test_5@example.com"
  };

  public static List<List<string>> GetMultiple
  {
   get
   {
    if (Contacts.Count <= 0)
    {
     Contacts.Add(File1);
     Contacts.Add(File2);
     Contacts.Add(File3);
    }
    return Contacts;
   }
  }
 }
}

6.到这里,我们的准备工作基本做得差不多了,最后我们只需要在DownloadController控制器中实现两个Action,一个为:DownloadSingle(提供下载单个文件的功能),另一个为:DownloadZip(提供打包压缩多个文件并下载的功能)。具体的DownloadController完整代码如下:

using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Ionic.Zip;
using WebApiDownload.Models;
using System;
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Web;


namespace WebApiDownload.Controllers
{
 [RoutePrefix("download")]
 public class DownloadController : ApiController
 {
  [HttpGet, Route("single")]
  public HttpResponseMessage DownloadSingle()
  {
   var response = new HttpResponseMessage();
   //从List集合中获取byte[]
   var bytes = DemoData.File1.Select(x => x + "\n").SelectMany(x => Encoding.UTF8.GetBytes(x)).ToArray();
   try
   {
    var fileName = string.Format("download_single_{0}.txt", DateTime.Now.ToString("yyyyMMddHHmmss"));
    var content = new ByteArrayContent(bytes);
    response.Content = content;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
     FileName = fileName
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
   }
   catch (Exception ex)
   {
    response.StatusCode = HttpStatusCode.InternalServerError;
    response.Content = new StringContent(ex.ToString());
   }
   return response;
  }
  [HttpGet, Route("zip")]
  public HttpResponseMessage DownloadZip()
  {
   var response = new HttpResponseMessage();
   try
   {
    var zipFileName = string.Format("download_compressed_{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));
    var downloadDir = HttpContext.Current.Server.MapPath($"~/downloads/download");
    var archive = $"{downloadDir}/{zipFileName}";
    var temp = HttpContext.Current.Server.MapPath("~/downloads/temp");

    // 清空临时文件夹中的所有临时文件
    Directory.EnumerateFiles(temp).ToList().ForEach(File.Delete);
    ClearDownloadDirectory(downloadDir);
    // 生成新的临时文件
    var counter = 1;
    foreach (var c in DemoData.GetMultiple)
    {
     var fileName = string.Format("each_file_{0}_{1}.txt", counter, DateTime.Now.ToString("yyyyMMddHHmmss"));
     if (c.Count <= 0)
     {
      continue;
     }
     var docPath = string.Format("{0}/{1}", temp, fileName);
     File.WriteAllLines(docPath, c, Encoding.UTF8);
     counter++;
    }
    Thread.Sleep(500);
    using (var zip = new ZipFile())
    {
     // Make zip file
     zip.AddDirectory(temp);
     zip.Save(archive);
    }
    response.Content = new StreamContent(new FileStream(archive, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = zipFileName };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
   }
   catch (Exception ex)
   {
    response.StatusCode = HttpStatusCode.InternalServerError;
    response.Content = new StringContent(ex.ToString());
   }
   return response;
  }

  private void ClearDownloadDirectory(string directory)
  {
   var files = Directory.GetFiles(directory);
   foreach (var file in files)
   {
    try
    {
     File.Delete(file);
    }
    catch
    {
    }
   }
  }
 }
}

到此,本示例的实现代码部分就完成了,如果我们此时打开地址:http://localhost:63161/download/single,浏览器会弹出保存文件的提示窗口,如下:

https://cdn.zhanzhang360.cn/imgupload/006845/2016062309583714.png

保存此文件后,打开它我们会看到我们的示例数据已被保存到本地了,如下:

https://cdn.zhanzhang360.cn/imgupload/006845/2016062309583815.png

同样的,下载压缩文件你只需要访问地址:localhost:63161/download/zip 即可,笔者就不再演示了。

最后,附上本示例项目的完整源代码,点击这里下载

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多