ASP.NET(C#) Web Api通过文件流下载文件到本地实例

来源:互联网 发布:mac os 打开文件夹 编辑:程序博客网 时间:2024/05/29 14:24

下载文件到本地是很多项目开发中需要实现的一个很简单的功能。说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是ASP.NET Web Api方式返回HttpResponseMessage下载文件到本地。实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的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);      }    }  }}

实现以上控制器后,我们可以直接打开这个api的地址(示例中的地址为:http://localhost:60560/download/get_demo_file),即可弹出下载文件的对话框了,如图:asp-net-web-api-download-file当然,也可以直接通过示例项目首页的下载链接体验,点击“下载示例文件”按钮,将会弹出保存文件的提示。 好了,示例比较简单,不用多说了。点击这里下载示例源码。

原创粉丝点击