您现在的位置是:网站首页> 编程资料编程资料
ASP.NET(C#) Web Api通过文件流下载文件的实例_实用技巧_
2023-05-24
356人已围观
简介 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 当然,也可以直接通过示例项目首页的下载链接体验,点击“下载示例文件”按钮,将会弹出保存文件的提示。 好了,示例比较简单,不用多说了。点击这里下载示例源码。
以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- 详解ABP框架中领域层的领域事件Domain events_基础应用_
- 解析ABP框架中的事务处理和工作单元_实用技巧_
- 详解ABP框架中的数据过滤器与数据传输对象的使用_基础应用_
- .NET实现简易的文件增量备份程序_实用技巧_
- asp.net core实现文件上传功能_实用技巧_
- 详解ASP.NET数据绑定操作中Repeater控件的用法_实用技巧_
- 总结Visual Studio下ASP.NET模板化控件中的数据绑定_实用技巧_
- ASP.NET框架中的数据绑定概要与数据绑定表达式的使用_实用技巧_
- Asp.net自定义控件之单选、多选控件_实用技巧_
- Asp.net自定义控件之加载层_实用技巧_
