webApi——通過文件流下載文件的實例

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);
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章