ASP.NET Web API 2 之檔案下載

來源:互聯網
上載者:User

標籤:blog   檔案類型   tle   new   ext   etl   head   wan   summary   

?  前言

目前 ASP.NET Web API 的應用非常廣泛,主要承載著服務端與用戶端的資料轉送與處理,如果需要使用 Web API 實現檔案下載,該 實現呢,其實也是比較簡單,以下樣本用於下載安卓的 .apk 檔案。

 

1.   C# 代碼

/// <summary>

/// 擷取最新 Apk 檔案。

/// </summary>

/// <param name="request"></param>

/// <returns></returns>

[Route("getLatest"), HttpGet]

[AllowAnonymous]

public HttpResponseMessage GetLatest(HttpRequestMessage request)

{

    var appVersionInfo = appManageService.GetLatest();

    string vp = appVersionInfo.VersionPath;     //http://xxx.xxx.xx.xx:81/xxxxx/xxx/3.0.6_20171017181838121.apk

    int lastIndex = vp.LastIndexOf("/");

    string fileName = "Yoca_{0}".Fmt(vp.Substring(lastIndex + 1, vp.Length - (lastIndex + 1)));

 

    byte[] bytes = null;

    WebRequest webRequest = (WebRequest)HttpWebRequest.Create(vp);

    using (WebResponse webResponse = webRequest.GetResponse())

    {

        using (var stream = webResponse.GetResponseStream())

        {

            bytes = new byte[webResponse.ContentLength];

            stream.Read(bytes, 0, bytes.Length);

        }

    }

 

    var response = request.CreateResponse();

    response.Content = new ByteArrayContent(bytes ?? new byte[0]);

    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(

        "application/vnd.android.package-archive");

    response.Content.Headers.ContentDisposition =

        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")

    {

        FileName = fileName

    };

    return response;

}

 

2.   說明

1)   以上代碼:首先,從資料庫中讀取最新的 .apk 檔案路徑(網路URI);然後,使用 WebRequest 等對象擷取該檔案的響應流;最後,將擷取的 byte 數組轉為 ByteArrayContent 對象,以響應 HTTP 訊息。

2)   注意:需要根據不同的檔案類型,設定響應的 ContentType 值,可參考:http://www.runoob.com/http/http-content-type.html

3)   其實,很多檔案下載都是使用這種方式,比如匯出 excel 或者 csv 檔案等。

ASP.NET Web API 2 之檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.