Web Api通過文件流下載文件到本地實例


最近項目里面需要和C++的客戶端互動,其中一個接口就是需要提供文件下載的接口,保證C++項目調用這個接口的時候能夠正常下載文件到本地。參考了一下網上的代碼,其原理就是讀取服務器上指定路徑的文件流,並將文件流包裝成返回的HttpResponseMessage的StreamContent。具體實現代碼如下:

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.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WebAPI.Controllers
{
    public class DownloadFileController : ApiController
    {
        /// <summary>
        /// 從WebAPI下載文件
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult GetFileFromWebApi()
        {
            var browser = String.Empty;
            if (HttpContext.Current.Request.UserAgent != null)
            {
                browser = HttpContext.Current.Request.UserAgent.ToUpper();
            }
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content", "標准事件.png");
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            FileStream fileStream = File.OpenRead(filePath);
            httpResponseMessage.Content = new StreamContent(fileStream);
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName =
                    browser.Contains("FIREFOX")
                        ? Path.GetFileName(filePath)
                        : HttpUtility.UrlEncode(Path.GetFileName(filePath))
                //FileName = HttpUtility.UrlEncode(Path.GetFileName(filePath))
            };

            return ResponseMessage(httpResponseMessage);
        }
    }
}

實現以上控制器后,我們可以直接在瀏覽器中請求這個api的地址(示例中的地址為:localhost:55603/api/DownloadFile/GetFileFromWebApi),即可彈出下載文件的對話框了,如圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM