ASP.NET(C#) Web Api通過文件流下載文件的實(shí)例

字號:


    這篇文章主要介紹了ASP.NET(C#) Web Api通過文件流下載文件的方法,提供源碼下載,需要的朋友可以參考下。
    下載文件到本地是很多項(xiàng)目開發(fā)中需要實(shí)現(xiàn)的一個(gè)很簡單的功能。說簡單,是從具體的代碼實(shí)現(xiàn)上來說的,.NET的文件下載方式有很多種,本示例給大家介紹的是ASP.NET Web Api方式返回HttpResponseMessage下載文件到本地。實(shí)現(xiàn)的方法很簡單,其中就是讀取服務(wù)器的指定路徑文件流,將其做為返回的HttpResponseMessage的Content。直接貼出DownloadController控件器的代碼:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Web.Http;
    namespace DownloadFileFromWebApi.Controllers
    {
     [RoutePrefix("download")]
     public class DownloadController : ApiController
     {
     [Route("get_demo_file")]
     public HttpResponseMessage GetFileFromWebApi()
     {
      try
      {
      var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/download/EditPlus64_xp85.com.zip");
      var stream = new FileStream(FilePath, FileMode.Open);
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
      response.Content = new StreamContent(stream);
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { 
      FileName="Wep Api Demo File.zip"
      };
      return response;
      }
      catch
      {
      return new HttpResponseMessage(HttpStatusCode.NoContent);
      }
     }
     }
    }
    以上就是本文的全部內(nèi)容,希望能給大家一個(gè)參考