网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 ASP.NET(C#) Web Api通过文件流下载文件的实例
内容
    这篇文章主要介绍了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);
      }
     }
     }
    }
    以上就是本文的全部内容,希望能给大家一个参考
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/19 9:06:22