服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET(C#) Web Api通过文件流下载文件的实例

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

2020-01-15 13:44yourber ASP.NET教程

这篇文章主要介绍了ASP.NET(C#) Web Api通过文件流下载文件的方法,提供源码下载,需要的朋友可以参考下。

下载文件到本地是很多项目开发中需要实现的一个很简单的功能。说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是ASP.NET Web Api方式返回HttpResponseMessage下载文件到本地。实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的HttpResponseMessage的Content。直接贴出DownloadController控件器的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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 当然,也可以直接通过示例项目首页的下载链接体验,点击“下载示例文件”按钮,将会弹出保存文件的提示。 好了,示例比较简单,不用多说了。点击这里下载示例源码。

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐