標籤: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 之檔案下載