佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > ASP.NET Web Api 2實現(xiàn)多文件打包并下載文件的實例

ASP.NET Web Api 2實現(xiàn)多文件打包并下載文件的實例

熱門標簽:智能手機 呼叫中心 地方門戶網(wǎng)站 蘋果 服務(wù)器配置 電子圍欄 硅谷的囚徒呼叫中心 解決方案

最近由于工作和個人事務(wù),站點也好久沒更新了,但這并不影響我對.NET的熱情。站點的更新工作還是得想辦法抽時間來完成的。

今天利用中午的時間來寫一篇關(guān)于Asp.Net Web Api下載文件的文章,之前我也寫過類似的文章,請見:《ASP.NET(C#) Web Api通過文件流下載文件的實例》

本文以這篇文章的基礎(chǔ),提供了ByteArrayContent的下載以及在下載多個文件時實現(xiàn)在服務(wù)器對多文件進行壓縮打包后下載的功能。

關(guān)于本文中實現(xiàn)的在服務(wù)器端用.NET壓縮打包文件功能的過程中,使用到了一個第方類庫:DotNetZip,具體的使用將在正文中涉及。好了,描述了這么多前言,下面我們進入本文示例的正文。

1.首先創(chuàng)建名為:WebApiDownload的Web Api 項目(C#);

2.接著新建一個空的控制器,命名為:DownloadController;

3.創(chuàng)建一些打包文件和存放臨時文件的文件夾(downloads),具體請看本文最后提供的示例項目代碼

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

搜索到DotNetZip安裝包后,進行安裝,以便用于本項目將要實現(xiàn)多文件打包壓縮的功能,如下圖:

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

5.在Models文件夾下創(chuàng)建一個示例數(shù)據(jù)的類,名為:DemoData,其中的成員和實現(xiàn)如下:

using System.Collections.Generic;


namespace WebApiDownload.Models
{
 public class DemoData
 {
  public static readonly ListListstring>> Contacts = new ListListstring>>();
  public static readonly Liststring> File1 = new Liststring>
  {
   "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 Liststring> File2 = new Liststring>
  {
   "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 Liststring> File3 = new Liststring>
  {
   "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 ListListstring>> GetMultiple
  {
   get
   {
    if (Contacts.Count = 0)
    {
     Contacts.Add(File1);
     Contacts.Add(File2);
     Contacts.Add(File3);
    }
    return Contacts;
   }
  }
 }
}

6.到這里,我們的準備工作基本做得差不多了,最后我們只需要在DownloadController控制器中實現(xiàn)兩個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
    {
    }
   }
  }
 }
}

到此,本示例的實現(xiàn)代碼部分就完成了,如果我們此時打開地址:http://localhost:63161/download/single,瀏覽器會彈出保存文件的提示窗口,如下:

保存此文件后,打開它我們會看到我們的示例數(shù)據(jù)已被保存到本地了,如下:

同樣的,下載壓縮文件你只需要訪問地址:localhost:63161/download/zip 即可,筆者就不再演示了。

最后,附上本示例項目的完整源代碼,點擊這里下載。

以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • 創(chuàng)建一個完整的ASP.NET Web API項目
  • ASP.NET中Web API的簡單實例
  • ASP.NET MVC Web API HttpClient簡介
  • 支持Ajax跨域訪問ASP.NET Web Api 2(Cors)的示例教程
  • ASP.NET Web API教程 創(chuàng)建Admin視圖詳細介紹
  • ASP.NET Web API如何將注釋自動生成幫助文檔
  • ASP.NET Web API教程 創(chuàng)建Admin控制器實例分享
  • ASP.NET Web API教程 創(chuàng)建域模型的方法詳細介紹
  • .Net Web Api中利用FluentValidate進行參數(shù)驗證的方法

標簽:德宏 佳木斯 玉林 房產(chǎn) 呂梁 泰安 喀什

巨人網(wǎng)絡(luò)通訊聲明:本文標題《ASP.NET Web Api 2實現(xiàn)多文件打包并下載文件的實例》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    蓝山县| 洛南县| 墨玉县| 永新县| 偃师市| 衡阳县| 常德市| 逊克县| 芜湖市| 旺苍县| 大冶市| 威海市| 贡山| 沐川县| 靖江市| 皮山县| 濮阳县| 星座| 陆丰市| 长顺县| 广宗县| 怀来县| 永定县| 江口县| 玉门市| 车险| 富蕴县| 皮山县| 连州市| 烟台市| 云霄县| 天津市| 沈阳市| 海城市| 宣汉县| 建湖县| 深水埗区| 普格县| 夹江县| 健康| 金乡县|