zoukankan      html  css  js  c++  java
  • ASP.NET(C#) Web Api通过文件流下载文件到本地实例

    下载文件到本地是很多项目开发中需要实现的一个很简单的功能。说简单,是从具体的代码实现上来说的,.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当然,也可以直接通过示例项目首页的下载链接体验,点击“下载示例文件”按钮,将会弹出保存文件的提示。 好了,示例比较简单,不用多说了。点击这里下载示例源码。

  • 相关阅读:
    【Mybatis】 JdbcType 与 JavaType对应关系
    【入门知识】虚拟机化概念
    【Ubuntu 16】安装deb
    【Ubuntu 16】安装eclipse
    【刷题】HDU 4405 Aeroplane chess
    【刷题】BZOJ 3998 [TJOI2015]弦论
    【刷题】SPOJ 1812 LCS2
    【刷题】BZOJ 2882 工艺
    【刷题】UOJ #171 【WC2016】挑战NPC
    【刷题】UOJ #79 一般图最大匹配
  • 原文地址:https://www.cnblogs.com/soundcode/p/6217016.html
Copyright © 2011-2022 走看看