webApi——通过文件流下载文件的实例

来源:互联网 发布:淘宝开店需要电脑吗 编辑:程序博客网 时间:2024/05/15 15:51

View

<div class="jumbotron">    <h1>Web Api下载文件示例</h1>    <p><a href="http://localhost:60560/api/download/get_demo_file" class="btn btn-primary btn-lg">下载示例文件 &raquo;</a></p></div>

这里写图片描述


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{    /// <summary>    /// 实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的HttpResponseMessage的Content    /// </summary>    [RoutePrefix("api/download")]    public class DownloadController : ApiController    {        [HttpGet,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);            }        }    }}
0 0
原创粉丝点击